<!DOCTYPE html>


<html lang="en">


<head>
  <meta charset="utf-8" />
    
  <meta name="description" content="小人物,码农" />
  
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
  <title>
    第四章 运算符 |  歆雨小屋
  </title>
  <meta name="generator" content="hexo-theme-ayer">
  
  <link rel="shortcut icon" href="/favicon.ico" />
  
  
<link rel="stylesheet" href="/dist/main.css">

  
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/css/remixicon.min.css">

  
<link rel="stylesheet" href="/css/custom.css">

  
  
<script src="https://cdn.jsdelivr.net/npm/pace-js@1.0.2/pace.min.js"></script>

  
  

  

<link rel="alternate" href="/atom.xml" title="歆雨小屋" type="application/atom+xml">
</head>

</html>

<body>
  <div id="app">
    
      
    <main class="content on">
      <section class="outer">
  <article
  id="post-第四章 运算符"
  class="article article-type-post"
  itemscope
  itemprop="blogPost"
  data-scroll-reveal
>
  <div class="article-inner">
    
    <header class="article-header">
       
<h1 class="article-title sea-center" style="border-left:0" itemprop="name">
  第四章 运算符
</h1>
 

    </header>
     
    <div class="article-meta">
      <a href="/2020/07/25/%E7%AC%AC%E5%9B%9B%E7%AB%A0%20%E8%BF%90%E7%AE%97%E7%AC%A6/" class="article-date">
  <time datetime="2020-07-25T14:26:31.000Z" itemprop="datePublished">2020-07-25</time>
</a> 
  <div class="article-category">
    <a class="article-category-link" href="/categories/Java%E7%BC%96%E7%A8%8B%E6%80%9D%E6%83%B3/">Java编程思想</a>
  </div>
  
<div class="word_count">
    <span class="post-time">
        <span class="post-meta-item-icon">
            <i class="ri-quill-pen-line"></i>
            <span class="post-meta-item-text"> Word count:</span>
            <span class="post-count">12.9k</span>
        </span>
    </span>

    <span class="post-time">
        &nbsp; | &nbsp;
        <span class="post-meta-item-icon">
            <i class="ri-book-open-line"></i>
            <span class="post-meta-item-text"> Reading time≈</span>
            <span class="post-count">54 min</span>
        </span>
    </span>
</div>
 
    </div>
      
    <div class="tocbot"></div>




  
    <div class="article-entry" itemprop="articleBody">
       
  <!-- Operators -->

<blockquote>
<p>运算符操纵数据。</p>
</blockquote>
<p>Java 是从 C++ 的基础上做了一些改进和简化发展而成的。对于 C/C++ 程序员来说，Java 的运算符并不陌生。如果你已了解 C 或 C++，大可以跳过本章和下一章，直接阅读 Java 与 C/C++ 不同的地方。</p>
<p>如果理解这两章的内容对你来说还有点困难，那么我推荐你先了解下 《Thinking in C》 再继续后面的学习。 这本书现在可以在 <a href="http://www.OnJava8.com]">www.OnJava8.com</a> 上免费下载。它的内容包含音频讲座、幻灯片、练习和解答，专门用于帮助你快速掌握学习 Java 所需的基础知识。</p>
<!-- Using-Java-Operators -->
<a id="more"></a>
<h2 id="开始使用"><a href="#开始使用" class="headerlink" title="开始使用"></a>开始使用</h2><p>运算符接受一个或多个参数并生成新值。这个参数与普通方法调用的形式不同，但效果是相同的。加法 <code>+</code>、减法 <code>-</code>、乘法 <code>*</code>、除法 <code>/</code> 以及赋值 <code>=</code> 在任何编程语言中的工作方式都是类似的。所有运算符都能根据自己的运算对象生成一个值。除此以外，一些运算符可改变运算对象的值，这叫作“副作用”（<strong>Side Effect</strong>）。运算符最常见的用途就是修改自己的运算对象，从而产生副作用。但要注意生成的值亦可由没有副作用的运算符生成。</p>
<p>几乎所有运算符都只能操作基本类型（Primitives）。唯一的例外是 <code>=</code>、<code>==</code> 和 <code>!=</code>，它们能操作所有对象（这也是令人混淆的一个地方）。除此以外，<strong>String</strong> 类支持 <code>+</code> 和 <code>+=</code>。</p>
<!-- Precedence -->
<h2 id="优先级"><a href="#优先级" class="headerlink" title="优先级"></a>优先级</h2><p>运算符的优先级决定了存在多个运算符时一个表达式各部分的运算顺序。Java 对运算顺序作出了特别的规定。其中，最简单的规则就是乘法和除法在加法和减法之前完成。程序员经常都会忘记其他优先级规则，所以应该用括号明确规定运算顺序。代码示例:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// operators/Precedence.java</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Precedence</span> </span>&#123;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> x = <span class="number">1</span>, y = <span class="number">2</span>, z = <span class="number">3</span>;</span><br><span class="line">        <span class="keyword">int</span> a = x + y - <span class="number">2</span>/<span class="number">2</span> + z; <span class="comment">// [1]</span></span><br><span class="line">        <span class="keyword">int</span> b = x + (y - <span class="number">2</span>)/(<span class="number">2</span> + z); <span class="comment">// [2]</span></span><br><span class="line">        System.out.println(<span class="string">"a = "</span> + a);</span><br><span class="line">        System.out.println(<span class="string">"b = "</span> + b);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>输出结果:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">a &#x3D; 5</span><br><span class="line">b &#x3D; 1</span><br></pre></td></tr></table></figure>

<p>这些语句看起来大致相同，但从输出中我们可以看出它们具有非常不同的含义，具体取决于括号的使用。</p>
<p>我们注意到，在 <code>System.out.println()</code> 语句中使用了 <code>+</code> 运算符。 但是在这里 <code>+</code> 代表的意思是字符串连接符。编译器会将 <code>+</code> 连接的非字符串尝试转换为字符串。上例中的输出结果说明了 a 和 b 都已经被转化成了字符串。</p>
<!-- Assignment -->
<h2 id="赋值"><a href="#赋值" class="headerlink" title="赋值"></a>赋值</h2><p>运算符的赋值是由符号 <code>=</code> 完成的。它代表着获取 <code>=</code> 右边的值并赋给左边的变量。右边可以是任何常量、变量或者可产生一个返回值的表达式。但左边必须是一个明确的、已命名的变量。也就是说，必须要有一个物理的空间来存放右边的值。举个例子来说，可将一个常数赋给一个变量（A = 4），但不可将任何东西赋给一个常数（比如不能 4 = A）。</p>
<p>基本类型的赋值都是直接的，而不像对象，赋予的只是其内存的引用。举个例子，a = b ，如果 b 是基本类型，那么赋值操作会将 b 的值复制一份给变量 a， 此后若 a 的值发生改变是不会影响到 b 的。作为一名程序员，这应该成为我们的常识。</p>
<p>如果是为对象赋值，那么结果就不一样了。对一个对象进行操作时，我们实际上操作的是它的引用。所以我们将右边的对象赋予给左边时，赋予的只是该对象的引用。此时，两者指向的堆中的对象还是同一个。代码示例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// operators/Assignment.java</span></span><br><span class="line"><span class="comment">// Assignment with objects is a bit tricky</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Tank</span> </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> level;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Assignment</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        Tank t1 = <span class="keyword">new</span> Tank();</span><br><span class="line">        Tank t2 = <span class="keyword">new</span> Tank();</span><br><span class="line">        t1.level = <span class="number">9</span>;</span><br><span class="line">        t2.level = <span class="number">47</span>;</span><br><span class="line">        System.out.println(<span class="string">"1: t1.level: "</span> + t1.level +</span><br><span class="line">            <span class="string">", t2.level: "</span> + t2.level);</span><br><span class="line">        t1 = t2;</span><br><span class="line">        System.out.println(<span class="string">"2: t1.level: "</span> + t1.level +</span><br><span class="line">            <span class="string">", t2.level: "</span> + t2.level);</span><br><span class="line">        t1.level = <span class="number">27</span>;</span><br><span class="line">        System.out.println(<span class="string">"3: t1.level: "</span> + t1.level +</span><br><span class="line">            <span class="string">", t2.level: "</span> + t2.level);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>输出结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">1: t1.level: 9, t2.level: 47</span><br><span class="line">2: t1.level: 47, t2.level: 47</span><br><span class="line">3: t1.level: 27, t2.level: 27</span><br></pre></td></tr></table></figure>

<p>这是一个简单的 <code>Tank</code> 类，在 <code>main()</code> 方法创建了两个实例对象。 两个对象的 <code>level</code> 属性分别被赋予不同的值。 然后，t2 的值被赋予给 t1。在许多编程语言里，预期的结果是 t1 和 t2 的值会一直相对独立。但是，在 Java 中，由于赋予的只是对象的引用，改变 t1 也就改变了 t2。 这是因为 t1 和 t2 此时指向的是堆中同一个对象。（t1 原始对象的引用在 t2 赋值给其时丢失，它引用的对象会在垃圾回收时被清理）。</p>
<p>这种现象通常称为别名（aliasing），这是 Java 处理对象的一种基本方式。但是假若你不想出现这里的别名引起混淆的话，你可以这么做。代码示例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">t1.level = t2.level;</span><br></pre></td></tr></table></figure>

<p>较之前的做法，这样做保留了两个单独的对象，而不是丢弃一个并将 t1 和 t2 绑定到同一个对象。但是这样的操作有点违背 Java 的设计原则。对象的赋值是个需要重视的环节，否则你可能收获意外的“惊喜”。</p>
 <!-- Aliasing During Method Calls -->
<h3 id="方法调用中的别名现象"><a href="#方法调用中的别名现象" class="headerlink" title="方法调用中的别名现象"></a>方法调用中的别名现象</h3><p>当我们把对象传递给方法时，会发生别名现象。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// operators/PassObject.java</span></span><br><span class="line"><span class="comment">// 正在传递的对象可能不是你之前使用的</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Letter</span> </span>&#123;</span><br><span class="line">    <span class="keyword">char</span> c;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">PassObject</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">f</span><span class="params">(Letter y)</span> </span>&#123;</span><br><span class="line">        y.c = <span class="string">'z'</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        Letter x = <span class="keyword">new</span> Letter();</span><br><span class="line">        x.c = <span class="string">'a'</span>;</span><br><span class="line">        System.out.println(<span class="string">"1: x.c: "</span> + x.c);</span><br><span class="line">        f(x);</span><br><span class="line">        System.out.println(<span class="string">"2: x.c: "</span> + x.c);</span><br><span class="line">     &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>输出结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">1: x.c: a</span><br><span class="line">2: x.c: z</span><br></pre></td></tr></table></figure>

<p>在许多编程语言中，方法 <code>f()</code> 似乎会在内部复制其参数 <strong>Letter y</strong>。但是一旦传递了一个引用，那么实际上 <code>y.c =&#39;z&#39;;</code> 是在方法 <code>f()</code> 之外改变对象。别名现象以及其解决方案是个复杂的问题，在附录中有包含：<a href="./Appendix-Passing-and-Returning-Objects.md">对象传递和返回</a>。意识到这一点，我们可以警惕类似的陷阱。</p>
<!-- Mathematical Operators -->
<h2 id="算术运算符"><a href="#算术运算符" class="headerlink" title="算术运算符"></a>算术运算符</h2><p>Java 的基本算术运算符与其他大多编程语言是相同的。其中包括加号 <code>+</code>、减号 <code>-</code>、除号 <code>/</code>、乘号 <code>*</code> 以及取模 <code>%</code>（从整数除法中获得余数）。整数除法会直接砍掉小数，而不是进位。</p>
<p>Java 也用一种与 C++ 相同的简写形式同时进行运算和赋值操作，由运算符后跟等号表示，并且与语言中的所有运算符一致（只要有意义）。  可用 x += 4 来表示：将 x 的值加上4的结果再赋值给 x。更多代码示例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// operators/MathOps.java</span></span><br><span class="line"><span class="comment">// The mathematical operators</span></span><br><span class="line"><span class="keyword">import</span> java.util.*;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MathOps</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// Create a seeded random number generator:</span></span><br><span class="line">        Random rand = <span class="keyword">new</span> Random(<span class="number">47</span>);</span><br><span class="line">        <span class="keyword">int</span> i, j, k;</span><br><span class="line">        <span class="comment">// Choose value from 1 to 100:</span></span><br><span class="line">        j = rand.nextInt(<span class="number">100</span>) + <span class="number">1</span>;</span><br><span class="line">        System.out.println(<span class="string">"j : "</span> + j);</span><br><span class="line">        k = rand.nextInt(<span class="number">100</span>) + <span class="number">1</span>;</span><br><span class="line">        System.out.println(<span class="string">"k : "</span> + k);</span><br><span class="line">        i = j + k;</span><br><span class="line">        System.out.println(<span class="string">"j + k : "</span> + i);</span><br><span class="line">        i = j - k;</span><br><span class="line">        System.out.println(<span class="string">"j - k : "</span> + i);</span><br><span class="line">        i = k / j;</span><br><span class="line">        System.out.println(<span class="string">"k / j : "</span> + i);</span><br><span class="line">        i = k * j;</span><br><span class="line">        System.out.println(<span class="string">"k * j : "</span> + i);</span><br><span class="line">        i = k % j;</span><br><span class="line">        System.out.println(<span class="string">"k % j : "</span> + i);</span><br><span class="line">        j %= k;</span><br><span class="line">        System.out.println(<span class="string">"j %= k : "</span> + j);</span><br><span class="line">        <span class="comment">// 浮点运算测试</span></span><br><span class="line">        <span class="keyword">float</span> u, v, w; <span class="comment">// Applies to doubles, too</span></span><br><span class="line">        v = rand.nextFloat();</span><br><span class="line">        System.out.println(<span class="string">"v : "</span> + v);</span><br><span class="line">        w = rand.nextFloat();</span><br><span class="line">        System.out.println(<span class="string">"w : "</span> + w);</span><br><span class="line">        u = v + w;</span><br><span class="line">        System.out.println(<span class="string">"v + w : "</span> + u);</span><br><span class="line">        u = v - w;</span><br><span class="line">        System.out.println(<span class="string">"v - w : "</span> + u);</span><br><span class="line">        u = v * w;</span><br><span class="line">        System.out.println(<span class="string">"v * w : "</span> + u);</span><br><span class="line">        u = v / w;</span><br><span class="line">        System.out.println(<span class="string">"v / w : "</span> + u);</span><br><span class="line">        <span class="comment">// 下面的操作同样适用于 char, </span></span><br><span class="line">        <span class="comment">// byte, short, int, long, and double:</span></span><br><span class="line">        u += v;</span><br><span class="line">        System.out.println(<span class="string">"u += v : "</span> + u);</span><br><span class="line">        u -= v;</span><br><span class="line">        System.out.println(<span class="string">"u -= v : "</span> + u);</span><br><span class="line">        u *= v;</span><br><span class="line">        System.out.println(<span class="string">"u *= v : "</span> + u);</span><br><span class="line">        u /= v;</span><br><span class="line">        System.out.println(<span class="string">"u /= v : "</span> + u);    </span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>输出结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">j : 59</span><br><span class="line">k : 56</span><br><span class="line">j + k : 115</span><br><span class="line">j - k : 3</span><br><span class="line">k &#x2F; j : 0</span><br><span class="line">k * j : 3304</span><br><span class="line">k % j : 56</span><br><span class="line">j %&#x3D; k : 3</span><br><span class="line">v : 0.5309454</span><br><span class="line">w : 0.0534122</span><br><span class="line">v + w : 0.5843576</span><br><span class="line">v - w : 0.47753322</span><br><span class="line">v * w : 0.028358962</span><br><span class="line">v &#x2F; w : 9.940527</span><br><span class="line">u +&#x3D; v : 10.471473</span><br><span class="line">u -&#x3D; v : 9.940527</span><br><span class="line">u *&#x3D; v : 5.2778773</span><br><span class="line">u &#x2F;&#x3D; v : 9.940527</span><br></pre></td></tr></table></figure>

<p>为了生成随机数字，程序首先创建一个 <strong>Random</strong> 对象。不带参数的 <strong>Random</strong> 对象会利用当前的时间用作随机数生成器的“种子”（seed），从而为程序的每次执行生成不同的输出。在本书的示例中，重要的是每个示例末尾的输出尽可能一致，以便可以使用外部工具进行验证。所以我们通过在创建 <strong>Random</strong> 对象时提供种子（随机数生成器的初始化值，其始终为特定种子值产生相同的序列），让程序每次执行都生成相同的随机数，如此以来输出结果就是可验证的 [^1]。 若需要生成随机值，可删除代码示例中的种子参数。该对象通过调用方法 <code>nextInt()</code> 和 <code>nextFloat()</code>（还可以调用 <code>nextLong()</code> 或 <code>nextDouble()</code>），使用 <strong>Random</strong> 对象生成许多不同类型的随机数。<code>nextInt()</code> 的参数设置生成的数字的上限，下限为零，为了避免零除的可能性，结果偏移1。</p>
<!-- Unary Minus and Plus Operators -->
<h3 id="一元加减运算符"><a href="#一元加减运算符" class="headerlink" title="一元加减运算符"></a>一元加减运算符</h3><p>一元加 <code>+</code> 减 <code>-</code> 运算符的操作和二元是相同的。编译器可自动识别使用何种方式解析运算：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">x = -a;</span><br></pre></td></tr></table></figure>

<p>上例的代码表意清晰，编译器可正确识别。下面再看一个示例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">x = a * -b;</span><br></pre></td></tr></table></figure>

<p>虽然编译器可以正确的识别，但是程序员可能会迷惑。为了避免混淆，推荐下面的写法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">x = a * (-b);</span><br></pre></td></tr></table></figure>

<p>一元减号可以得到数据的负值。一元加号的作用相反，不过它唯一能影响的就是把较小的数值类型自动转换为 <strong>int</strong> 类型。</p>
<!-- Auto-Increment-and-Decrement -->
<h2 id="递增和递减"><a href="#递增和递减" class="headerlink" title="递增和递减"></a>递增和递减</h2><p>和 C 语言类似，Java 提供了许多快捷运算方式。快捷运算可使代码可读性，可写性都更强。其中包括递增 <code>++</code> 和递减 <code>--</code>，意为“增加或减少一个单位”。举个例子来说，假设 a 是一个 <strong>int</strong> 类型的值，则表达式 <code>++a</code> 就等价于 <code>a = a + 1</code>。 递增和递减运算符不仅可以修改变量，还可以生成变量的值。</p>
<p>每种类型的运算符，都有两个版本可供选用；通常将其称为“前缀”和“后缀”。“前递增”表示 <code>++</code> 运算符位于变量或表达式的前面；而“后递增”表示 <code>++</code> 运算符位于变量的后面。类似地，“前递减”意味着 <code>--</code> 运算符位于变量的前面；而“后递减”意味着 <code>--</code> 运算符位于变量的后面。对于前递增和前递减（如 <code>++a</code> 或 <code>--a</code>），会先执行递增/减运算，再返回值。而对于后递增和后递减（如 <code>a++</code> 或 <code>a--</code>），会先返回值，再执行递增/减运算。代码示例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// operators/AutoInc.java</span></span><br><span class="line"><span class="comment">// 演示 ++ 和 -- 运算符</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">AutoInc</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> i = <span class="number">1</span>;</span><br><span class="line">        System.out.println(<span class="string">"i: "</span> + i);</span><br><span class="line">        System.out.println(<span class="string">"++i: "</span> + ++i); <span class="comment">// 前递增</span></span><br><span class="line">        System.out.println(<span class="string">"i++: "</span> + i++); <span class="comment">// 后递增</span></span><br><span class="line">        System.out.println(<span class="string">"i: "</span> + i);</span><br><span class="line">        System.out.println(<span class="string">"--i: "</span> + --i); <span class="comment">// 前递减</span></span><br><span class="line">        System.out.println(<span class="string">"i--: "</span> + i--); <span class="comment">// 后递减</span></span><br><span class="line">        System.out.println(<span class="string">"i: "</span> + i);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>输出结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">i: 1</span><br><span class="line">++i: 2</span><br><span class="line">i++: 2</span><br><span class="line">i: 3</span><br><span class="line">--i: 2</span><br><span class="line">i--: 2</span><br><span class="line">i: 1</span><br></pre></td></tr></table></figure>

<p>对于前缀形式，我们将在执行递增/减操作后获取值；使用后缀形式，我们将在执行递增/减操作之前获取值。它们是唯一具有“副作用”的运算符（除那些涉及赋值的以外） —— 它们修改了操作数的值。</p>
<p>C++ 名称来自于递增运算符，暗示着“比 C 更进一步”。在早期的 Java 演讲中，<em>Bill Joy</em>（Java 作者之一）说“<strong>Java = C++ –</strong>”（C++ 减减），意味着 Java 在 C++  的基础上减少了许多不必要的东西，因此语言更简单。随着进一步地学习，我们会发现 Java 的确有许多地方相对 C++ 来说更简便，但是在其他方面，难度并不会比 C++ 小多少。</p>
<!-- Relational-Operators -->
<h2 id="关系运算符"><a href="#关系运算符" class="headerlink" title="关系运算符"></a>关系运算符</h2><p>关系运算符会通过产生一个布尔（<strong>boolean</strong>）结果来表示操作数之间的关系。如果关系为真，则结果为 <strong>true</strong>，如果关系为假，则结果为 <strong>false</strong>。关系运算符包括小于 <code>&lt;</code>，大于 <code>&gt;</code>，小于或等于 <code>&lt;=</code>，大于或等于 <code>&gt;=</code>，等于 <code>==</code> 和不等于 <code>！=</code>。<code>==</code> 和 <code>!=</code> 可用于所有基本类型，但其他运算符不能用于基本类型 <strong>boolean</strong>，因为布尔值只能表示 <strong>true</strong> 或 <strong>false</strong>，所以比较它们之间的“大于”或“小于”没有意义。</p>
<!-- Testing Object Equivalence -->
<h3 id="测试对象等价"><a href="#测试对象等价" class="headerlink" title="测试对象等价"></a>测试对象等价</h3><p>关系运算符 <code>==</code> 和 <code>!=</code> 同样适用于所有对象之间的比较运算，但它们比较的内容却经常困扰 Java 的初学者。下面是代码示例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// operators/Equivalence.java</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Equivalence</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        Integer n1 = <span class="number">47</span>;</span><br><span class="line">        Integer n2 = <span class="number">47</span>;</span><br><span class="line">        System.out.println(n1 == n2);</span><br><span class="line">        System.out.println(n1 != n2);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>输出结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">true</span><br><span class="line">false</span><br></pre></td></tr></table></figure>

<p>表达式 <code>System.out.println(n1 == n2)</code> 将会输出比较的结果。因为两个 <strong>Integer</strong> 对象相同，所以先输出 <strong>true</strong>，再输出 <strong>false</strong>。但是，尽管对象的内容一样，对象的引用却不一样。<code>==</code> 和 <code>!=</code> 比较的是对象引用，所以输出实际上应该是先输出 <strong>false</strong>，再输出 <strong>true</strong>（译者注：如果你把 47 改成 128，那么打印的结果就是这样，因为 Integer 内部维护着一个 IntegerCache 的缓存，默认缓存范围是 [-128, 127]，所以 [-128, 127] 之间的值用 <code>==</code> 和 <code>!=</code> 比较也能能到正确的结果，但是不推荐用关系运算符比较，具体见 JDK 中的 Integer 类源码）。</p>
<p>那么怎么比较两个对象的内容是否相同呢？你必须使用所有对象（不包括基本类型）中都存在的 <code>equals()</code> 方法，下面是如何使用 <code>equals()</code> 方法的示例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// operators/EqualsMethod.java</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">EqualsMethod</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        Integer n1 = <span class="number">47</span>;</span><br><span class="line">        Integer n2 = <span class="number">47</span>;</span><br><span class="line">        System.out.println(n1.equals(n2));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>输出结果:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">true</span></span><br></pre></td></tr></table></figure>

<p>上例的结果看起来是我们所期望的。但其实事情并非那么简单。下面我们来创建自己的类：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// operators/EqualsMethod2.java</span></span><br><span class="line"><span class="comment">// 默认的 equals() 方法没有比较内容</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Value</span> </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> i;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">EqualsMethod2</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        Value v1 = <span class="keyword">new</span> Value();</span><br><span class="line">        Value v2 = <span class="keyword">new</span> Value();</span><br><span class="line">        v1.i = v2.i = <span class="number">100</span>;</span><br><span class="line">        System.out.println(v1.equals(v2));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>输出结果:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">false</span></span><br></pre></td></tr></table></figure>

<p>上例的结果再次令人困惑：结果是 <strong>false</strong>。原因： <code>equals()</code> 的默认行为是比较对象的引用而非具体内容。因此，除非你在新类中覆写 <code>equals()</code> 方法，否则我们将获取不到想要的结果。不幸的是，在学习 <a href="./08-Reuse.md">复用</a>（<strong>Reuse</strong>） 章节后我们才能接触到“覆写”（<strong>Override</strong>），并且直到 <a href="./Appendix-Collection-Topics.md">附录:集合主题</a>，才能知道定义 <code>equals()</code> 方法的正确方式，但是现在明白 <code>equals()</code> 行为方式也可能为你节省一些时间。</p>
<p>大多数 Java 库类通过覆写 <code>equals()</code> 方法比较对象的内容而不是其引用。</p>
<!-- Logical Operators -->
<h2 id="逻辑运算符"><a href="#逻辑运算符" class="headerlink" title="逻辑运算符"></a>逻辑运算符</h2><p>每个逻辑运算符 <code>&amp;&amp;</code> （<strong>AND</strong>）、<code>||</code>（<strong>OR</strong>）和 <code>!</code>（<strong>非</strong>）根据参数的逻辑关系生成布尔值 <code>true</code> 或 <code>false</code>。下面的代码示例使用了关系运算符和逻辑运算符：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// operators/Bool.java</span></span><br><span class="line"><span class="comment">// 关系运算符和逻辑运算符</span></span><br><span class="line"><span class="keyword">import</span> java.util.*;</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Bool</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        Random rand = <span class="keyword">new</span> Random(<span class="number">47</span>);</span><br><span class="line">        <span class="keyword">int</span> i = rand.nextInt(<span class="number">100</span>);</span><br><span class="line">        <span class="keyword">int</span> j = rand.nextInt(<span class="number">100</span>);</span><br><span class="line">        System.out.println(<span class="string">"i = "</span> + i);</span><br><span class="line">        System.out.println(<span class="string">"j = "</span> + j);</span><br><span class="line">        System.out.println(<span class="string">"i &gt; j is "</span> + (i &gt; j));</span><br><span class="line">        System.out.println(<span class="string">"i &lt; j is "</span> + (i &lt; j));</span><br><span class="line">        System.out.println(<span class="string">"i &gt;= j is "</span> + (i &gt;= j));</span><br><span class="line">        System.out.println(<span class="string">"i &lt;= j is "</span> + (i &lt;= j));</span><br><span class="line">        System.out.println(<span class="string">"i == j is "</span> + (i == j));</span><br><span class="line">        System.out.println(<span class="string">"i != j is "</span> + (i != j));</span><br><span class="line">        <span class="comment">// 将 int 作为布尔处理不是合法的 Java 写法</span></span><br><span class="line">        <span class="comment">//- System.out.println("i &amp;&amp; j is " + (i &amp;&amp; j));</span></span><br><span class="line">        <span class="comment">//- System.out.println("i || j is " + (i || j));</span></span><br><span class="line">        <span class="comment">//- System.out.println("!i is " + !i);</span></span><br><span class="line">        System.out.println(<span class="string">"(i &lt; 10) &amp;&amp; (j &lt; 10) is "</span></span><br><span class="line">        + ((i &lt; <span class="number">10</span>) &amp;&amp; (j &lt; <span class="number">10</span>)) );</span><br><span class="line">        System.out.println(<span class="string">"(i &lt; 10) || (j &lt; 10) is "</span></span><br><span class="line">        + ((i &lt; <span class="number">10</span>) || (j &lt; <span class="number">10</span>)) );</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>输出结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">i &#x3D; 58</span><br><span class="line">j &#x3D; 55</span><br><span class="line">i &gt; j is true</span><br><span class="line">i &lt; j is false</span><br><span class="line">i &gt;&#x3D; j is true</span><br><span class="line">i &lt;&#x3D; j is false</span><br><span class="line">i &#x3D;&#x3D; j is false</span><br><span class="line">i !&#x3D; j is true</span><br><span class="line">(i &lt; 10) &amp;&amp; (j &lt; 10) is false</span><br><span class="line">(i &lt; 10) || (j &lt; 10) is false</span><br></pre></td></tr></table></figure>

<p>在 Java 逻辑运算中，我们不能像 C/C++ 那样使用非布尔值， 而仅能使用 <strong>AND</strong>、 <strong>OR</strong>、 <strong>NOT</strong>。上面的例子中，我们将使用非布尔值的表达式注释掉了（你可以看到表达式前面是 //-）。但是，后续的表达式使用关系比较生成布尔值，然后对结果使用了逻辑运算。请注意，如果在预期为 <strong>String</strong> 类型的位置使用 <strong>boolean</strong> 类型的值，则结果会自动转为适当的文本格式（即 “true” 或 “false” 字符串）。</p>
<p>我们可以将前一个程序中 <strong>int</strong> 的定义替换为除 <strong>boolean</strong> 之外的任何其他基本数据类型。但请注意，<strong>float</strong> 类型的数值比较非常严格，只要两个数字的最小位不同则两个数仍然不相等；只要数字最小位是大于 0 的，那么它就不等于 0。</p>
<!-- Short-Circuiting -->
<h3 id="短路"><a href="#短路" class="headerlink" title="短路"></a>短路</h3><p>逻辑运算符支持一种称为“短路”（short-circuiting）的现象。整个表达式会在运算到可以明确结果时就停止并返回结果，这意味着该逻辑表达式的后半部分不会被执行到。代码示例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// operators / ShortCircuit.java </span></span><br><span class="line"><span class="comment">// 逻辑运算符的短路行为</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ShortCircuit</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">static</span> <span class="keyword">boolean</span> <span class="title">test1</span><span class="params">(<span class="keyword">int</span> val)</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"test1("</span> + val + <span class="string">")"</span>);</span><br><span class="line">        System.out.println(<span class="string">"result: "</span> + (val &lt; <span class="number">1</span>));</span><br><span class="line">        <span class="keyword">return</span> val &lt; <span class="number">1</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">static</span> <span class="keyword">boolean</span> <span class="title">test2</span><span class="params">(<span class="keyword">int</span> val)</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"test2("</span> + val + <span class="string">")"</span>);</span><br><span class="line">        System.out.println(<span class="string">"result: "</span> + (val &lt; <span class="number">2</span>));</span><br><span class="line">        <span class="keyword">return</span> val &lt; <span class="number">2</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">static</span> <span class="keyword">boolean</span> <span class="title">test3</span><span class="params">(<span class="keyword">int</span> val)</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"test3("</span> + val + <span class="string">")"</span>);</span><br><span class="line">        System.out.println(<span class="string">"result: "</span> + (val &lt; <span class="number">3</span>));</span><br><span class="line">        <span class="keyword">return</span> val &lt; <span class="number">3</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">boolean</span> b = test1(<span class="number">0</span>) &amp;&amp; test2(<span class="number">2</span>) &amp;&amp; test3(<span class="number">2</span>);</span><br><span class="line">        System.out.println(<span class="string">"expression is "</span> + b);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>输出结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">test1(0)</span><br><span class="line">result: true</span><br><span class="line">test2(2)</span><br><span class="line">result: false</span><br><span class="line">expression is false</span><br></pre></td></tr></table></figure>

<p>每个测试都对参数执行比较并返回 <code>true</code> 或 <code>false</code>。同时控制台也会在方法执行时打印他们的执行状态。 下面的表达式：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">test1（<span class="number">0</span>）&amp;&amp; test2（<span class="number">2</span>）&amp;&amp; test3（<span class="number">2</span>）</span><br></pre></td></tr></table></figure>

<p>可能你的预期是程序会执行 3 个 <strong>test</strong> 方法并返回。我们来分析一下：第一个方法的结果返回 <code>true</code>，因此表达式会继续走下去。紧接着，第二个方法的返回结果是 <code>false</code>。这就代表这整个表达式的结果肯定为 <code>false</code>，所以就没有必要再判断剩下的表达式部分了。</p>
<p>所以，运用“短路”可以节省部分不必要的运算，从而提高程序潜在的性能。</p>
<!-- Literals -->
<h2 id="字面值常量"><a href="#字面值常量" class="headerlink" title="字面值常量"></a>字面值常量</h2><p>通常，当我们向程序中插入一个字面值常量（<strong>Literal</strong>）时，编译器会确切地识别它的类型。当类型不明确时，必须辅以字面值常量关联来帮助编译器识别。代码示例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// operators/Literals.java</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Literals</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> i1 = <span class="number">0x2f</span>; <span class="comment">// 16进制 (小写)</span></span><br><span class="line">        System.out.println(</span><br><span class="line">        <span class="string">"i1: "</span> + Integer.toBinaryString(i1));</span><br><span class="line">        <span class="keyword">int</span> i2 = <span class="number">0X2F</span>; <span class="comment">// 16进制 (大写)</span></span><br><span class="line">        System.out.println(</span><br><span class="line">        <span class="string">"i2: "</span> + Integer.toBinaryString(i2));</span><br><span class="line">        <span class="keyword">int</span> i3 = <span class="number">0177</span>; <span class="comment">// 8进制 (前导0)</span></span><br><span class="line">        System.out.println(</span><br><span class="line">        <span class="string">"i3: "</span> + Integer.toBinaryString(i3));</span><br><span class="line">        <span class="keyword">char</span> c = <span class="number">0xffff</span>; <span class="comment">// 最大 char 型16进制值</span></span><br><span class="line">        System.out.println(</span><br><span class="line">        <span class="string">"c: "</span> + Integer.toBinaryString(c));</span><br><span class="line">        <span class="keyword">byte</span> b = <span class="number">0x7f</span>; <span class="comment">// 最大 byte 型16进制值  10101111;</span></span><br><span class="line">        System.out.println(</span><br><span class="line">        <span class="string">"b: "</span> + Integer.toBinaryString(b));</span><br><span class="line">        <span class="keyword">short</span> s = <span class="number">0x7fff</span>; <span class="comment">// 最大 short 型16进制值</span></span><br><span class="line">        System.out.println(</span><br><span class="line">        <span class="string">"s: "</span> + Integer.toBinaryString(s));</span><br><span class="line">        <span class="keyword">long</span> n1 = <span class="number">200L</span>; <span class="comment">// long 型后缀</span></span><br><span class="line">        <span class="keyword">long</span> n2 = <span class="number">200l</span>; <span class="comment">// long 型后缀 (容易与数值1混淆)</span></span><br><span class="line">        <span class="keyword">long</span> n3 = <span class="number">200</span>;</span><br><span class="line">    </span><br><span class="line">        <span class="comment">// Java 7 二进制字面值常量:</span></span><br><span class="line">        <span class="keyword">byte</span> blb = (<span class="keyword">byte</span>)<span class="number">0b00110101</span>;</span><br><span class="line">        System.out.println(</span><br><span class="line">        <span class="string">"blb: "</span> + Integer.toBinaryString(blb));</span><br><span class="line">        <span class="keyword">short</span> bls = (<span class="keyword">short</span>)<span class="number">0B0010111110101111</span>;</span><br><span class="line">        System.out.println(</span><br><span class="line">        <span class="string">"bls: "</span> + Integer.toBinaryString(bls));</span><br><span class="line">        <span class="keyword">int</span> bli = <span class="number">0b00101111101011111010111110101111</span>;</span><br><span class="line">        System.out.println(</span><br><span class="line">        <span class="string">"bli: "</span> + Integer.toBinaryString(bli));</span><br><span class="line">        <span class="keyword">long</span> bll = <span class="number">0b00101111101011111010111110101111</span>;</span><br><span class="line">        System.out.println(</span><br><span class="line">        <span class="string">"bll: "</span> + Long.toBinaryString(bll));</span><br><span class="line">        <span class="keyword">float</span> f1 = <span class="number">1</span>;</span><br><span class="line">        <span class="keyword">float</span> f2 = <span class="number">1F</span>; <span class="comment">// float 型后缀</span></span><br><span class="line">        <span class="keyword">float</span> f3 = <span class="number">1f</span>; <span class="comment">// float 型后缀</span></span><br><span class="line">        <span class="keyword">double</span> d1 = <span class="number">1</span>d; <span class="comment">// double 型后缀</span></span><br><span class="line">        <span class="keyword">double</span> d2 = <span class="number">1</span>D; <span class="comment">// double 型后缀</span></span><br><span class="line">        <span class="comment">// (long 型的字面值同样适用于十六进制和8进制 )</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>输出结果:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">i1: 101111</span><br><span class="line">i2: 101111</span><br><span class="line">i3: 1111111</span><br><span class="line">c: 1111111111111111</span><br><span class="line">b: 1111111</span><br><span class="line">s: 111111111111111</span><br><span class="line">blb: 110101</span><br><span class="line">bls: 10111110101111</span><br><span class="line">bli: 101111101011111010111110101111</span><br><span class="line">bll: 101111101011111010111110101111</span><br></pre></td></tr></table></figure>

<p>在文本值的后面添加字符可以让编译器识别该文本值的类型。对于 <strong>Long</strong> 型数值，结尾使用大写 <code>L</code> 或小写 <code>l</code> 皆可（不推荐使用 <code>l</code>，因为容易与阿拉伯数值 1 混淆）。大写 <code>F</code> 或小写 <code>f</code> 表示 <strong>float</strong> 浮点数。大写 <code>D</code> 或小写 <code>d</code> 表示 <strong>double</strong> 双精度。</p>
<p>十六进制（以 16 为基数），适用于所有整型数据类型，由前导 <code>0x</code> 或 <code>0X</code> 表示，后跟 0-9 或 a-f （大写或小写）。如果我们在初始化某个类型的数值时，赋值超出其范围，那么编译器会报错（不管值的数字形式如何）。在上例的代码中，<strong>char</strong>、<strong>byte</strong> 和 <strong>short</strong> 的值已经是最大了。如果超过这些值，编译器将自动转型为 <strong>int</strong>，并且提示我们需要声明强制转换（强制转换将在本章后面定义），意味着我们已越过该类型的范围界限。</p>
<p>八进制（以 8 为基数）由 0~7 之间的数字和前导零 <code>0</code> 表示。</p>
<p>Java 7 引入了二进制的字面值常量，由前导 <code>0b</code> 或 <code>0B</code> 表示，它可以初始化所有的整数类型。</p>
<p>使用整型数值类型时，显示其二进制形式会很有用。在 Long 型和 Integer 型中这很容易实现，调用其静态的 <code>toBinaryString()</code> 方法即可。 但是请注意，若将较小的类型传递给 <strong>Integer.</strong><code>toBinaryString()</code> 时，类型将自动转换为 <strong>int</strong>。</p>
<!-- Underscores in Literals -->
<h3 id="下划线"><a href="#下划线" class="headerlink" title="下划线"></a>下划线</h3><p>Java 7 中有一个深思熟虑的补充：我们可以在数字字面量中包含下划线 <code>_</code>，以使结果更清晰。这对于大数值的分组特别有用。代码示例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// operators/Underscores.java</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Underscores</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">double</span> d = <span class="number">341_435_936.445_667</span>;</span><br><span class="line">        System.out.println(d);</span><br><span class="line">        <span class="keyword">int</span> bin = <span class="number">0b0010_1111_1010_1111_1010_1111_1010_1111</span>;</span><br><span class="line">        System.out.println(Integer.toBinaryString(bin));</span><br><span class="line">        System.out.printf(<span class="string">"%x%n"</span>, bin); <span class="comment">// [1]</span></span><br><span class="line">        <span class="keyword">long</span> hex = <span class="number">0x7f_e9_b7_aa</span>;</span><br><span class="line">        System.out.printf(<span class="string">"%x%n"</span>, hex);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>输出结果:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">3.41435936445667E8</span><br><span class="line">101111101011111010111110101111</span><br><span class="line">2fafafaf</span><br><span class="line">7fe9b7aa</span><br></pre></td></tr></table></figure>

<p>下面是合理使用的规则：</p>
<ol>
<li>仅限单 <code>_</code>，不能多条相连。</li>
<li>数值开头和结尾不允许出现 <code>_</code>。</li>
<li><code>F</code>、<code>D</code> 和 <code>L</code>的前后禁止出现 <code>_</code>。</li>
<li>二进制前导 <code>b</code> 和 十六进制 <code>x</code> 前后禁止出现 <code>_</code>。</li>
</ol>
<p>[1] 注意 <code>%n</code>的使用。熟悉 C 风格的程序员可能习惯于看到 <code>\n</code> 来表示换行符。问题在于它给你的是一个“Unix风格”的换行符。此外，如果我们使用的是 Windows，则必须指定 <code>\r\n</code>。这种差异的包袱应该由编程语言来解决。这就是 Java 用 <code>%n</code> 实现的可以忽略平台间差异而生成适当的换行符，但只有当你使用 <code>System.out.printf()</code> 或 <code>System.out.format()</code> 时。对于 <code>System.out.println()</code>，我们仍然必须使用 <code>\n</code>；如果你使用 <code>%n</code>，<code>println()</code> 只会输出 <code>%n</code> 而不是换行符。</p>
<!-- Exponential Notation -->
<h3 id="指数计数法"><a href="#指数计数法" class="headerlink" title="指数计数法"></a>指数计数法</h3><p>指数总是采用一种我认为很不直观的记号方法:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// operators/Exponents.java</span></span><br><span class="line"><span class="comment">// "e" 表示 10 的几次幂</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Exponents</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// 大写 E 和小写 e 的效果相同:</span></span><br><span class="line">        <span class="keyword">float</span> expFloat = <span class="number">1.39e-43f</span>;</span><br><span class="line">        expFloat = <span class="number">1.39E-43f</span>;</span><br><span class="line">        System.out.println(expFloat);</span><br><span class="line">        <span class="keyword">double</span> expDouble = <span class="number">47e47</span>d; <span class="comment">// 'd' 是可选的</span></span><br><span class="line">        <span class="keyword">double</span> expDouble2 = <span class="number">47e47</span>; <span class="comment">// 自动转换为 double</span></span><br><span class="line">        System.out.println(expDouble);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>输出结果:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">1.39E-43</span><br><span class="line">4.7E48</span><br></pre></td></tr></table></figure>

<p>在科学与工程学领域，<strong>e</strong> 代表自然对数的基数，约等于 2.718 （Java 里用一种更精确的 <strong>double</strong> 值 <strong>Math.E</strong> 来表示自然对数）。指数表达式 “1.39 x e-43”，意味着 “1.39 × 2.718 的 -43 次方”。然而，自 FORTRAN 语言发明后，人们自然而然地觉得e 代表 “10 的几次幂”。这种做法显得颇为古怪，因为 FORTRAN 最初是为科学与工程领域设计的。</p>
<p>理所当然，它的设计者应对这样的混淆概念持谨慎态度 [^2]。但不管怎样，这种特别的表达方法在 C，C++ 以及现在的 Java 中顽固地保留下来了。所以倘若习惯 e 作为自然对数的基数使用，那么在 Java 中看到类似“1.39e-43f”这样的表达式时，请转换你的思维，从程序设计的角度思考它；它真正的含义是 “1.39 × 10 的 -43 次方”。</p>
<p>注意如果编译器能够正确地识别类型，就不必使用后缀字符。对于下述语句：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">long</span> n3 = <span class="number">200</span>;</span><br></pre></td></tr></table></figure>

<p>它并不存在含糊不清的地方，所以 200 后面的 L 大可省去。然而，对于下述语句：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">float</span> f4 = <span class="number">1e-43f</span>; <span class="comment">//10 的幂数</span></span><br></pre></td></tr></table></figure>

<p>编译器通常会将指数作为 <strong>double</strong> 类型来处理，所以假若没有这个后缀字符 <code>f</code>，编译器就会报错，提示我们应该将 <strong>double</strong> 型转换成 <strong>float</strong> 型。</p>
<!-- Bitwise-Operators -->
<h2 id="位运算符"><a href="#位运算符" class="headerlink" title="位运算符"></a>位运算符</h2><p>位运算符允许我们操作一个整型数字中的单个二进制位。位运算符会对两个整数对应的位执行布尔代数，从而产生结果。</p>
<p>位运算源自 C 语言的底层操作。我们经常要直接操纵硬件，频繁设置硬件寄存器内的二进制位。Java 的设计初衷是电视机顶盒嵌入式开发，所以这种底层的操作仍被保留了下来。但是，你可能不会使用太多位运算。</p>
<p>若两个输入位都是 1，则按位“与运算符” <code>&amp;</code> 运算后结果是 1，否则结果是 0。若两个输入位里至少有一个是 1，则按位“或运算符” <code>|</code> 运算后结果是 1；只有在两个输入位都是 0 的情况下，运算结果才是 0。若两个输入位的某一个是 1，另一个不是 1，那么按位“异或运算符” <code>^</code> 运算后结果才是 1。按位“非运算符” <code>~</code> 属于一元运算符；它只对一个自变量进行操作（其他所有运算符都是二元运算符）。按位非运算后结果与输入位相反。例如输入 0，则输出 1；输入 1，则输出 0。</p>
<p>位运算符和逻辑运算符都使用了同样的字符，只不过数量不同。位短，所以位运算符只有一个字符。位运算符可与等号 <code>=</code> 联合使用以接收结果及赋值：<code>&amp;=</code>，<code>|=</code> 和 <code>^=</code> 都是合法的（由于 <code>~</code> 是一元运算符，所以不可与 <code>=</code> 联合使用）。</p>
<p>我们将 <strong>Boolean</strong> 类型被视为“单位值”（one-bit value），所以它多少有些独特的地方。我们可以对 boolean 型变量执行与、或、异或运算，但不能执行非运算（大概是为了避免与逻辑“非”混淆）。对于布尔值，位运算符具有与逻辑运算符相同的效果，只是它们不会中途“短路”。此外，针对布尔值进行的位运算为我们新增了一个“异或”逻辑运算符，它并未包括在逻辑运算符的列表中。在移位表达式中，禁止使用布尔值，原因将在下面解释。</p>
<!-- Shift Operators -->
<h2 id="移位运算符"><a href="#移位运算符" class="headerlink" title="移位运算符"></a>移位运算符</h2><p>移位运算符面向的运算对象也是二进制的“位”。它们只能用于处理整数类型（基本类型的一种）。左移位运算符 <code>&lt;&lt;</code> 能将其左边的运算对象向左移动右侧指定的位数（在低位补 0）。右移位运算符 <code>&gt;&gt;</code> 则相反。右移位运算符有“正”、“负”值：若值为正，则在高位插入 0；若值为负，则在高位插入 1。Java 也添加了一种“不分正负”的右移位运算符（&gt;&gt;&gt;），它使用了“零扩展”（zero extension）：无论正负，都在高位插入 0。这一运算符是 C/C++ 没有的。</p>
<p>如果移动 <strong>char</strong>、<strong>byte</strong> 或 <strong>short</strong>，则会在移动发生之前将其提升为 <strong>int</strong>，结果为 <strong>int</strong>。仅使用右值（rvalue）的 5 个低阶位。这可以防止我们移动超过 <strong>int</strong> 范围的位数。若对一个 <strong>long</strong> 值进行处理，最后得到的结果也是 <strong>long</strong>。</p>
<p>移位可以与等号 <code>&lt;&lt;=</code> 或 <code>&gt;&gt;=</code> 或 <code>&gt;&gt;&gt;=</code> 组合使用。左值被替换为其移位运算后的值。但是，问题来了，当无符号右移与赋值相结合时，若将其与 <strong>byte</strong> 或 <strong>short</strong> 一起使用的话，则结果错误。取而代之的是，它们被提升为 <strong>int</strong> 型并右移，但在重新赋值时被截断。在这种情况下，结果为 -1。下面是代码示例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// operators/URShift.java</span></span><br><span class="line"><span class="comment">// 测试无符号右移</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">URShift</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> i = -<span class="number">1</span>;</span><br><span class="line">        System.out.println(Integer.toBinaryString(i));</span><br><span class="line">        i &gt;&gt;&gt;= <span class="number">10</span>;</span><br><span class="line">        System.out.println(Integer.toBinaryString(i));</span><br><span class="line">        <span class="keyword">long</span> l = -<span class="number">1</span>;</span><br><span class="line">        System.out.println(Long.toBinaryString(l));</span><br><span class="line">        l &gt;&gt;&gt;= <span class="number">10</span>;</span><br><span class="line">        System.out.println(Long.toBinaryString(l));</span><br><span class="line">        <span class="keyword">short</span> s = -<span class="number">1</span>;</span><br><span class="line">        System.out.println(Integer.toBinaryString(s));</span><br><span class="line">        s &gt;&gt;&gt;= <span class="number">10</span>;</span><br><span class="line">        System.out.println(Integer.toBinaryString(s));</span><br><span class="line">        <span class="keyword">byte</span> b = -<span class="number">1</span>;</span><br><span class="line">        System.out.println(Integer.toBinaryString(b));</span><br><span class="line">        b &gt;&gt;&gt;= <span class="number">10</span>;</span><br><span class="line">        System.out.println(Integer.toBinaryString(b));</span><br><span class="line">        b = -<span class="number">1</span>;</span><br><span class="line">        System.out.println(Integer.toBinaryString(b));</span><br><span class="line">        System.out.println(Integer.toBinaryString(b&gt;&gt;&gt;<span class="number">10</span>));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>输出结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">11111111111111111111111111111111</span><br><span class="line">1111111111111111111111</span><br><span class="line">1111111111111111111111111111111111111111111111111111111111111111</span><br><span class="line">111111111111111111111111111111111111111111111111111111</span><br><span class="line">11111111111111111111111111111111</span><br><span class="line">11111111111111111111111111111111</span><br><span class="line">11111111111111111111111111111111</span><br><span class="line">11111111111111111111111111111111</span><br><span class="line">11111111111111111111111111111111</span><br><span class="line">1111111111111111111111</span><br></pre></td></tr></table></figure>


<p>在上例中，结果并未重新赋值给变量 <strong>b</strong> ，而是直接打印出来，因此一切正常。下面是一个涉及所有位运算符的代码示例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// operators/BitManipulation.java</span></span><br><span class="line"><span class="comment">// 使用位运算符</span></span><br><span class="line"><span class="keyword">import</span> java.util.*;</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">BitManipulation</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        Random rand = <span class="keyword">new</span> Random(<span class="number">47</span>);</span><br><span class="line">        <span class="keyword">int</span> i = rand.nextInt();</span><br><span class="line">        <span class="keyword">int</span> j = rand.nextInt();</span><br><span class="line">        printBinaryInt(<span class="string">"-1"</span>, -<span class="number">1</span>);</span><br><span class="line">        printBinaryInt(<span class="string">"+1"</span>, +<span class="number">1</span>);</span><br><span class="line">        <span class="keyword">int</span> maxpos = <span class="number">2147483647</span>;</span><br><span class="line">        printBinaryInt(<span class="string">"maxpos"</span>, maxpos);</span><br><span class="line">        <span class="keyword">int</span> maxneg = -<span class="number">2147483648</span>;</span><br><span class="line">        printBinaryInt(<span class="string">"maxneg"</span>, maxneg);</span><br><span class="line">        printBinaryInt(<span class="string">"i"</span>, i);</span><br><span class="line">        printBinaryInt(<span class="string">"~i"</span>, ~i);</span><br><span class="line">        printBinaryInt(<span class="string">"-i"</span>, -i);</span><br><span class="line">        printBinaryInt(<span class="string">"j"</span>, j);</span><br><span class="line">        printBinaryInt(<span class="string">"i &amp; j"</span>, i &amp; j);</span><br><span class="line">        printBinaryInt(<span class="string">"i | j"</span>, i | j);</span><br><span class="line">        printBinaryInt(<span class="string">"i ^ j"</span>, i ^ j);</span><br><span class="line">        printBinaryInt(<span class="string">"i &lt;&lt; 5"</span>, i &lt;&lt; <span class="number">5</span>);</span><br><span class="line">        printBinaryInt(<span class="string">"i &gt;&gt; 5"</span>, i &gt;&gt; <span class="number">5</span>);</span><br><span class="line">        printBinaryInt(<span class="string">"(~i) &gt;&gt; 5"</span>, (~i) &gt;&gt; <span class="number">5</span>);</span><br><span class="line">        printBinaryInt(<span class="string">"i &gt;&gt;&gt; 5"</span>, i &gt;&gt;&gt; <span class="number">5</span>);</span><br><span class="line">        printBinaryInt(<span class="string">"(~i) &gt;&gt;&gt; 5"</span>, (~i) &gt;&gt;&gt; <span class="number">5</span>);</span><br><span class="line">        <span class="keyword">long</span> l = rand.nextLong();</span><br><span class="line">        <span class="keyword">long</span> m = rand.nextLong();</span><br><span class="line">        printBinaryLong(<span class="string">"-1L"</span>, -<span class="number">1L</span>);</span><br><span class="line">        printBinaryLong(<span class="string">"+1L"</span>, +<span class="number">1L</span>);</span><br><span class="line">        <span class="keyword">long</span> ll = <span class="number">9223372036854775807L</span>;</span><br><span class="line">        printBinaryLong(<span class="string">"maxpos"</span>, ll);</span><br><span class="line">        <span class="keyword">long</span> lln = -<span class="number">9223372036854775808L</span>;</span><br><span class="line">        printBinaryLong(<span class="string">"maxneg"</span>, lln);</span><br><span class="line">        printBinaryLong(<span class="string">"l"</span>, l);</span><br><span class="line">        printBinaryLong(<span class="string">"~l"</span>, ~l);</span><br><span class="line">        printBinaryLong(<span class="string">"-l"</span>, -l);</span><br><span class="line">        printBinaryLong(<span class="string">"m"</span>, m);</span><br><span class="line">        printBinaryLong(<span class="string">"l &amp; m"</span>, l &amp; m);</span><br><span class="line">        printBinaryLong(<span class="string">"l | m"</span>, l | m);</span><br><span class="line">        printBinaryLong(<span class="string">"l ^ m"</span>, l ^ m);</span><br><span class="line">        printBinaryLong(<span class="string">"l &lt;&lt; 5"</span>, l &lt;&lt; <span class="number">5</span>);</span><br><span class="line">        printBinaryLong(<span class="string">"l &gt;&gt; 5"</span>, l &gt;&gt; <span class="number">5</span>);</span><br><span class="line">        printBinaryLong(<span class="string">"(~l) &gt;&gt; 5"</span>, (~l) &gt;&gt; <span class="number">5</span>);</span><br><span class="line">        printBinaryLong(<span class="string">"l &gt;&gt;&gt; 5"</span>, l &gt;&gt;&gt; <span class="number">5</span>);</span><br><span class="line">        printBinaryLong(<span class="string">"(~l) &gt;&gt;&gt; 5"</span>, (~l) &gt;&gt;&gt; <span class="number">5</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">printBinaryInt</span><span class="params">(String s, <span class="keyword">int</span> i)</span> </span>&#123;</span><br><span class="line">        System.out.println(</span><br><span class="line">        s + <span class="string">", int: "</span> + i + <span class="string">", binary:\n "</span> +</span><br><span class="line">        Integer.toBinaryString(i));</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">printBinaryLong</span><span class="params">(String s, <span class="keyword">long</span> l)</span> </span>&#123;</span><br><span class="line">        System.out.println(</span><br><span class="line">        s + <span class="string">", long: "</span> + l + <span class="string">", binary:\n "</span> +</span><br><span class="line">        Long.toBinaryString(l));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>输出结果（前 32 行）：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line">-1, int: -1, binary:</span><br><span class="line">11111111111111111111111111111111</span><br><span class="line">+1, int: 1, binary:</span><br><span class="line">1</span><br><span class="line">maxpos, int: 2147483647, binary:</span><br><span class="line">1111111111111111111111111111111</span><br><span class="line">maxneg, int: -2147483648, binary:</span><br><span class="line">10000000000000000000000000000000</span><br><span class="line">i, int: -1172028779, binary:</span><br><span class="line">10111010001001000100001010010101</span><br><span class="line">~i, int: 1172028778, binary:</span><br><span class="line"> 1000101110110111011110101101010</span><br><span class="line">-i, int: 1172028779, binary:</span><br><span class="line">1000101110110111011110101101011</span><br><span class="line">j, int: 1717241110, binary:</span><br><span class="line">1100110010110110000010100010110</span><br><span class="line">i &amp; j, int: 570425364, binary:</span><br><span class="line">100010000000000000000000010100</span><br><span class="line">i | j, int: -25213033, binary:</span><br><span class="line">11111110011111110100011110010111</span><br><span class="line">i ^ j, int: -595638397, binary:</span><br><span class="line">11011100011111110100011110000011</span><br><span class="line">i &lt;&lt; 5, int: 1149784736, binary:</span><br><span class="line">1000100100010000101001010100000</span><br><span class="line">i &gt;&gt; 5, int: -36625900, binary:</span><br><span class="line">11111101110100010010001000010100</span><br><span class="line">(~i) &gt;&gt; 5, int: 36625899, binary:</span><br><span class="line">10001011101101110111101011</span><br><span class="line">i &gt;&gt;&gt; 5, int: 97591828, binary:</span><br><span class="line">101110100010010001000010100</span><br><span class="line">(~i) &gt;&gt;&gt; 5, int: 36625899, binary:</span><br><span class="line">10001011101101110111101011</span><br><span class="line">    ...</span><br></pre></td></tr></table></figure>

<p>结尾的两个方法 <code>printBinaryInt()</code> 和 <code>printBinaryLong()</code> 分别操作一个 <strong>int</strong> 和 <strong>long</strong> 值，并转换为二进制格式输出，同时附有简要的文字说明。除了演示 <strong>int</strong> 和 <strong>long</strong> 的所有位运算符的效果之外，本示例还显示 <strong>int</strong> 和 <strong>long</strong> 的最小值、最大值、+1 和 -1 值，以便我们了解它们的形式。注意高位代表符号：0 表示正，1 表示负。上面显示了 <strong>int</strong> 部分的输出。以上数字的二进制表示形式是带符号的补码（2’s complement）。</p>
<!-- Ternary-if-else-Operator -->
<h2 id="三元运算符"><a href="#三元运算符" class="headerlink" title="三元运算符"></a>三元运算符</h2><p>三元运算符，也称为条件运算符。这种运算符比较罕见，因为它有三个运算对象。但它确实属于运算符的一种，因为它最终也会生成一个值。这与本章后一节要讲述的普通 <strong>if-else</strong> 语句是不同的。下面是它的表达式格式：</p>
<p><strong>布尔表达式 ? 值 1 : 值 2</strong></p>
<p>若表达式计算为 <strong>true</strong>，则返回结果 <strong>值 1</strong> ；如果表达式的计算为 <strong>false</strong>，则返回结果 <strong>值 2</strong>。</p>
<p>当然，也可以换用普通的 <strong>if-else</strong> 语句（在后面介绍），但三元运算符更加简洁。作为三元运算符的创造者， C 自诩为一门简练的语言。三元运算符的引入多半就是为了高效编程，但假若我们打算频繁使用它的话，还是先多作一些思量： 它易于产生可读性差的代码。与 <strong>if-else</strong> 不同的是，三元运算符是有返回结果的。请看下面的代码示例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// operators/TernaryIfElse.java</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">TernaryIfElse</span> </span>&#123;</span><br><span class="line">    </span><br><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">int</span> <span class="title">ternary</span><span class="params">(<span class="keyword">int</span> i)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> i &lt; <span class="number">10</span> ? i * <span class="number">100</span> : i * <span class="number">10</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">int</span> <span class="title">standardIfElse</span><span class="params">(<span class="keyword">int</span> i)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span>(i &lt; <span class="number">10</span>)</span><br><span class="line">        <span class="keyword">return</span> i * <span class="number">100</span>;</span><br><span class="line">    <span class="keyword">else</span></span><br><span class="line">        <span class="keyword">return</span> i * <span class="number">10</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        System.out.println(ternary(<span class="number">9</span>));</span><br><span class="line">        System.out.println(ternary(<span class="number">10</span>));</span><br><span class="line">        System.out.println(standardIfElse(<span class="number">9</span>));</span><br><span class="line">        System.out.println(standardIfElse(<span class="number">10</span>));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>输出结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">900</span><br><span class="line">100</span><br><span class="line">900</span><br><span class="line">100</span><br></pre></td></tr></table></figure>

<p>可以看出，<code>ternary()</code> 中的代码更简短。然而，<strong>standardIfElse()</strong> 中的代码更易理解且不要求更多的录入。所以我们在挑选三元运算符时，请务必权衡一下利弊。</p>
<!-- String-Operator-+-and-+= -->
<h2 id="字符串运算符"><a href="#字符串运算符" class="headerlink" title="字符串运算符"></a>字符串运算符</h2><p>这个运算符在 Java 里有一项特殊用途：连接字符串。这点已在前面展示过了。尽管与 <code>+</code> 的传统意义不符，但如此使用也还是比较自然的。这一功能看起来还不错，于是在 C++ 里引入了“运算符重载”机制，以便 C++ 程序员为几乎所有运算符增加特殊的含义。但遗憾得是，与 C++ 的一些限制结合以后，它变得复杂。这要求程序员在设计自己的类时必须对此有周全的考虑。虽然在 Java 中实现运算符重载机制并非难事（如 C# 所展示的，它具有简单的运算符重载），但因该特性过于复杂，因此 Java 并未实现它。</p>
<p>我们注意到运用 <code>String +</code> 时有一些有趣的现象。若表达式以一个 <strong>String</strong> 类型开头（编译器会自动将双引号 <code>&quot;&quot;</code> 标注的的字符序列转换为字符串），那么后续所有运算对象都必须是字符串。代码示例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// operators/StringOperators.java</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">StringOperators</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> x = <span class="number">0</span>, y = <span class="number">1</span>, z = <span class="number">2</span>;</span><br><span class="line">        String s = <span class="string">"x, y, z "</span>;</span><br><span class="line">        System.out.println(s + x + y + z);</span><br><span class="line">        <span class="comment">// 将 x 转换为字符串</span></span><br><span class="line">        System.out.println(x + <span class="string">" "</span> + s);</span><br><span class="line">        s += <span class="string">"(summed) = "</span>; </span><br><span class="line">        <span class="comment">// 级联操作</span></span><br><span class="line">        System.out.println(s + (x + y + z));</span><br><span class="line">        <span class="comment">// Integer.toString()方法的简写:</span></span><br><span class="line">        System.out.println(<span class="string">""</span> + x);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>输出结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">x, y, z 012</span><br><span class="line">0 x, y, z</span><br><span class="line">x, y, z (summed) &#x3D; 3</span><br><span class="line">0</span><br></pre></td></tr></table></figure>

<p><strong>注意</strong>：上例中第 1 输出语句的执行结果是 <code>012</code> 而并非 <code>3</code>，这是因为编译器将其分别转换为其字符串形式然后与字符串变量 <strong>s</strong> 连接。在第 2 条输出语句中，编译器将开头的变量转换为了字符串，由此可以看出，这种转换与数据的位置无关，只要当中有一条数据是字符串类型，其他非字符串数据都将被转换为字符串形式并连接。最后一条输出语句，我们可以看出 <code>+=</code> 运算符可以拼接其右侧的字符串连接结果并重赋值给自身变量 <code>s</code>。括号 <code>()</code> 可以控制表达式的计算顺序，以便在显示 <strong>int</strong> 之前对其进行实际求和。</p>
<p>请注意主方法中的最后一个例子：我们经常会看到一个空字符串 <code>&quot;&quot;</code> 跟着一个基本类型的数据。这样可以隐式地将其转换为字符串，以代替繁琐的显式调用方法（如这里可以使用 <strong>Integer.toString()</strong>）。</p>
<!-- Common-Pitfalls-When-Using-Operators -->
<h2 id="常见陷阱"><a href="#常见陷阱" class="headerlink" title="常见陷阱"></a>常见陷阱</h2><p>使用运算符时很容易犯的一个错误是，在还没搞清楚表达式的计算方式时就试图忽略括号 <code>()</code>。在 Java 中也一样。 在 C++ 中你甚至可能犯这样极端的错误.代码示例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">while</span>(x = y) &#123;</span><br><span class="line"><span class="comment">// ...</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>显然，程序员原意是测试等价性 <code>==</code>，而非赋值 <code>=</code>。若变量 <strong>y</strong> 非 0 的话，在 C/C++ 中，这样的赋值操作总会返回 <code>true</code>。于是，上面的代码示例将会无限循环。而在 Java 中，这样的表达式结果并不会转化为一个布尔值。 而编译器会试图把这个 <strong>int</strong> 型数据转换为预期应接收的布尔类型。最后，我们将会在试图运行前收到编译期错误。因此，Java 天生避免了这种陷阱发生的可能。</p>
<p>唯一有种情况例外：当变量 <code>x</code> 和 <code>y</code> 都是布尔值，例如  <code>x=y</code> 是一个逻辑表达式。除此之外，之前的那个例子，很大可能是错误。</p>
<p>在 C/C++ 里，类似的一个问题还有使用按位“与” <code>&amp;</code> 和“或” <code>|</code> 运算，而非逻辑“与” <code>&amp;&amp;</code> 和“或” <code>||</code>。就象 <code>=</code> 和 <code>==</code> 一样，键入一个字符当然要比键入两个简单。在 Java 中，编译器同样可防止这一点，因为它不允许我们强行使用另一种并不符的类型。</p>
<!-- Casting-Operators -->
<h2 id="类型转换"><a href="#类型转换" class="headerlink" title="类型转换"></a>类型转换</h2><p>“类型转换”（Casting）的作用是“与一个模型匹配”。在适当的时候，Java 会将一种数据类型自动转换成另一种。例如，假设我们为 <strong>float</strong> 变量赋值一个整数值，计算机会将 <strong>int</strong> 自动转换成 <strong>float</strong>。我们可以在程序未自动转换时显式、强制地使此类型发生转换。</p>
<p>要执行强制转换，需要将所需的数据类型放在任何值左侧的括号内，如下所示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// operators/Casting.java</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Casting</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> i = <span class="number">200</span>;</span><br><span class="line">        <span class="keyword">long</span> lng = (<span class="keyword">long</span>)i;</span><br><span class="line">        lng = i; <span class="comment">// 没有必要的类型提升</span></span><br><span class="line">        <span class="keyword">long</span> lng2 = (<span class="keyword">long</span>)<span class="number">200</span>;</span><br><span class="line">        lng2 = <span class="number">200</span>;</span><br><span class="line">        <span class="comment">// 类型收缩</span></span><br><span class="line">        i = (<span class="keyword">int</span>)lng2; <span class="comment">// Cast required</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>诚然，你可以这样地去转换一个数值类型的变量。但是上例这种做法是多余的：因为编译器会在必要时自动提升 <strong>int</strong> 型数据为 <strong>long</strong> 型。</p>
<p>当然，为了程序逻辑清晰或提醒自己留意，我们也可以显式地类型转换。在其他情况下，类型转换只有在代码编译时才显出其重要性。在 C/C++ 中，类型转换有时会让人头痛。在 Java 里，类型转换则是一种比较安全的操作。但是，若将数据类型进行“向下转换”（<strong>Narrowing Conversion</strong>）的操作（将容量较大的数据类型转换成容量较小的类型），可能会发生信息丢失的危险。此时，编译器会强迫我们进行转型，好比在提醒我们：该操作可能危险，若你坚持让我这么做，那么对不起，请明确需要转换的类型。 对于“向上转换”（<strong>Widening conversion</strong>），则不必进行显式的类型转换，因为较大类型的数据肯定能容纳较小类型的数据，不会造成任何信息的丢失。</p>
<p>除了布尔类型的数据，Java 允许任何基本类型的数据转换为另一种基本类型的数据。此外，类是不能进行类型转换的。为了将一个类转换为另一个类型，需要使用特殊的方法（后面将会学习到如何在父子类之间进行向上/向下转型，例如，“橡树”可以转换为“树”，反之亦然。而对于“岩石”是无法转换为“树”的）。</p>
<!-- Truncation and Rounding -->
<h3 id="截断和舍入"><a href="#截断和舍入" class="headerlink" title="截断和舍入"></a>截断和舍入</h3><p>在执行“向下转换”时，必须注意数据的截断和舍入问题。若从浮点值转换为整型值，Java 会做什么呢？例如：浮点数 29.7 被转换为整型值，结果会是 29 还是 30 呢？下面是代码示例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// operators/CastingNumbers.java</span></span><br><span class="line"><span class="comment">// 尝试转换 float 和 double 型数据为整型数据</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">CastingNumbers</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">double</span> above = <span class="number">0.7</span>, below = <span class="number">0.4</span>;</span><br><span class="line">        <span class="keyword">float</span> fabove = <span class="number">0.7f</span>, fbelow = <span class="number">0.4f</span>;</span><br><span class="line">        System.out.println(<span class="string">"(int)above: "</span> + (<span class="keyword">int</span>)above);</span><br><span class="line">        System.out.println(<span class="string">"(int)below: "</span> + (<span class="keyword">int</span>)below);</span><br><span class="line">        System.out.println(<span class="string">"(int)fabove: "</span> + (<span class="keyword">int</span>)fabove);</span><br><span class="line">        System.out.println(<span class="string">"(int)fbelow: "</span> + (<span class="keyword">int</span>)fbelow);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>输出结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">(int)above: 0</span><br><span class="line">(int)below: 0</span><br><span class="line">(int)fabove: 0</span><br><span class="line">(int)fbelow: 0</span><br></pre></td></tr></table></figure>

<p>因此，答案是，从 <strong>float</strong> 和 <strong>double</strong> 转换为整数值时，小数位将被截断。若你想对结果进行四舍五入，可以使用 <code>java.lang.Math</code> 的 <code>round()</code> 方法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// operators/RoundingNumbers.java</span></span><br><span class="line"><span class="comment">// float 和 double 类型数据的四舍五入</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">RoundingNumbers</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">double</span> above = <span class="number">0.7</span>, below = <span class="number">0.4</span>;</span><br><span class="line">        <span class="keyword">float</span> fabove = <span class="number">0.7f</span>, fbelow = <span class="number">0.4f</span>;</span><br><span class="line">        System.out.println(</span><br><span class="line">        <span class="string">"Math.round(above): "</span> + Math.round(above));</span><br><span class="line">        System.out.println(</span><br><span class="line">        <span class="string">"Math.round(below): "</span> + Math.round(below));</span><br><span class="line">        System.out.println(</span><br><span class="line">        <span class="string">"Math.round(fabove): "</span> + Math.round(fabove));</span><br><span class="line">        System.out.println(</span><br><span class="line">        <span class="string">"Math.round(fbelow): "</span> + Math.round(fbelow));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>输出结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">Math.round(above): 1</span><br><span class="line">Math.round(below): 0</span><br><span class="line">Math.round(fabove): 1</span><br><span class="line">Math.round(fbelow): 0</span><br></pre></td></tr></table></figure>

<p>因为 <code>round()</code> 方法是 <code>java.lang</code> 的一部分，所以我们无需通过 <code>import</code> 就可以使用。</p>
<!-- Promotion -->
<h3 id="类型提升"><a href="#类型提升" class="headerlink" title="类型提升"></a>类型提升</h3><p>你会发现，如果我们对小于 <strong>int</strong> 的基本数据类型（即 <strong>char</strong>、<strong>byte</strong> 或 <strong>short</strong>）执行任何算术或按位操作，这些值会在执行操作之前类型提升为 <strong>int</strong>，并且结果值的类型为 <strong>int</strong>。若想重新使用较小的类型，必须使用强制转换（由于重新分配回一个较小的类型，结果可能会丢失精度）。通常，表达式中最大的数据类型是决定表达式结果的数据类型。<strong>float</strong> 型和 <strong>double</strong> 型相乘，结果是 <strong>double</strong> 型的；<strong>int</strong> 和 <strong>long</strong> 相加，结果是 <strong>long</strong> 型。</p>
<!-- Java-Has-No-sizeof -->
<h2 id="Java没有sizeof"><a href="#Java没有sizeof" class="headerlink" title="Java没有sizeof"></a>Java没有sizeof</h2><p>在 C/C++ 中，经常需要用到 <code>sizeof()</code> 方法来获取数据项被分配的字节大小。C/C++ 中使用 <code>sizeof()</code> 最有说服力的原因是为了移植性，不同数据在不同机器上可能有不同的大小，所以在进行大小敏感的运算时，程序员必须对这些类型有多大做到心中有数。例如，一台计算机可用 32 位来保存整数，而另一台只用 16 位保存。显然，在第一台机器中，程序可保存更大的值。所以，移植是令 C/C++ 程序员颇为头痛的一个问题。</p>
<p>Java 不需要 <code>sizeof()</code> 方法来满足这种需求，因为所有类型的大小在不同平台上是相同的。我们不必考虑这个层次的移植问题 —— Java 本身就是一种“与平台无关”的语言。</p>
<!-- A-Compendium-of-Operators -->
<h2 id="运算符总结"><a href="#运算符总结" class="headerlink" title="运算符总结"></a>运算符总结</h2><p>上述示例分别向我们展示了哪些基本类型能被用于特定的运算符。基本上，下面的代码示例是对上述所有示例的重复，只不过概括了所有的基本类型。这个文件能被正确地编译，因为我已经把编译不通过的那部分用注释 <code>//</code> 过滤了。代码示例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br><span class="line">194</span><br><span class="line">195</span><br><span class="line">196</span><br><span class="line">197</span><br><span class="line">198</span><br><span class="line">199</span><br><span class="line">200</span><br><span class="line">201</span><br><span class="line">202</span><br><span class="line">203</span><br><span class="line">204</span><br><span class="line">205</span><br><span class="line">206</span><br><span class="line">207</span><br><span class="line">208</span><br><span class="line">209</span><br><span class="line">210</span><br><span class="line">211</span><br><span class="line">212</span><br><span class="line">213</span><br><span class="line">214</span><br><span class="line">215</span><br><span class="line">216</span><br><span class="line">217</span><br><span class="line">218</span><br><span class="line">219</span><br><span class="line">220</span><br><span class="line">221</span><br><span class="line">222</span><br><span class="line">223</span><br><span class="line">224</span><br><span class="line">225</span><br><span class="line">226</span><br><span class="line">227</span><br><span class="line">228</span><br><span class="line">229</span><br><span class="line">230</span><br><span class="line">231</span><br><span class="line">232</span><br><span class="line">233</span><br><span class="line">234</span><br><span class="line">235</span><br><span class="line">236</span><br><span class="line">237</span><br><span class="line">238</span><br><span class="line">239</span><br><span class="line">240</span><br><span class="line">241</span><br><span class="line">242</span><br><span class="line">243</span><br><span class="line">244</span><br><span class="line">245</span><br><span class="line">246</span><br><span class="line">247</span><br><span class="line">248</span><br><span class="line">249</span><br><span class="line">250</span><br><span class="line">251</span><br><span class="line">252</span><br><span class="line">253</span><br><span class="line">254</span><br><span class="line">255</span><br><span class="line">256</span><br><span class="line">257</span><br><span class="line">258</span><br><span class="line">259</span><br><span class="line">260</span><br><span class="line">261</span><br><span class="line">262</span><br><span class="line">263</span><br><span class="line">264</span><br><span class="line">265</span><br><span class="line">266</span><br><span class="line">267</span><br><span class="line">268</span><br><span class="line">269</span><br><span class="line">270</span><br><span class="line">271</span><br><span class="line">272</span><br><span class="line">273</span><br><span class="line">274</span><br><span class="line">275</span><br><span class="line">276</span><br><span class="line">277</span><br><span class="line">278</span><br><span class="line">279</span><br><span class="line">280</span><br><span class="line">281</span><br><span class="line">282</span><br><span class="line">283</span><br><span class="line">284</span><br><span class="line">285</span><br><span class="line">286</span><br><span class="line">287</span><br><span class="line">288</span><br><span class="line">289</span><br><span class="line">290</span><br><span class="line">291</span><br><span class="line">292</span><br><span class="line">293</span><br><span class="line">294</span><br><span class="line">295</span><br><span class="line">296</span><br><span class="line">297</span><br><span class="line">298</span><br><span class="line">299</span><br><span class="line">300</span><br><span class="line">301</span><br><span class="line">302</span><br><span class="line">303</span><br><span class="line">304</span><br><span class="line">305</span><br><span class="line">306</span><br><span class="line">307</span><br><span class="line">308</span><br><span class="line">309</span><br><span class="line">310</span><br><span class="line">311</span><br><span class="line">312</span><br><span class="line">313</span><br><span class="line">314</span><br><span class="line">315</span><br><span class="line">316</span><br><span class="line">317</span><br><span class="line">318</span><br><span class="line">319</span><br><span class="line">320</span><br><span class="line">321</span><br><span class="line">322</span><br><span class="line">323</span><br><span class="line">324</span><br><span class="line">325</span><br><span class="line">326</span><br><span class="line">327</span><br><span class="line">328</span><br><span class="line">329</span><br><span class="line">330</span><br><span class="line">331</span><br><span class="line">332</span><br><span class="line">333</span><br><span class="line">334</span><br><span class="line">335</span><br><span class="line">336</span><br><span class="line">337</span><br><span class="line">338</span><br><span class="line">339</span><br><span class="line">340</span><br><span class="line">341</span><br><span class="line">342</span><br><span class="line">343</span><br><span class="line">344</span><br><span class="line">345</span><br><span class="line">346</span><br><span class="line">347</span><br><span class="line">348</span><br><span class="line">349</span><br><span class="line">350</span><br><span class="line">351</span><br><span class="line">352</span><br><span class="line">353</span><br><span class="line">354</span><br><span class="line">355</span><br><span class="line">356</span><br><span class="line">357</span><br><span class="line">358</span><br><span class="line">359</span><br><span class="line">360</span><br><span class="line">361</span><br><span class="line">362</span><br><span class="line">363</span><br><span class="line">364</span><br><span class="line">365</span><br><span class="line">366</span><br><span class="line">367</span><br><span class="line">368</span><br><span class="line">369</span><br><span class="line">370</span><br><span class="line">371</span><br><span class="line">372</span><br><span class="line">373</span><br><span class="line">374</span><br><span class="line">375</span><br><span class="line">376</span><br><span class="line">377</span><br><span class="line">378</span><br><span class="line">379</span><br><span class="line">380</span><br><span class="line">381</span><br><span class="line">382</span><br><span class="line">383</span><br><span class="line">384</span><br><span class="line">385</span><br><span class="line">386</span><br><span class="line">387</span><br><span class="line">388</span><br><span class="line">389</span><br><span class="line">390</span><br><span class="line">391</span><br><span class="line">392</span><br><span class="line">393</span><br><span class="line">394</span><br><span class="line">395</span><br><span class="line">396</span><br><span class="line">397</span><br><span class="line">398</span><br><span class="line">399</span><br><span class="line">400</span><br><span class="line">401</span><br><span class="line">402</span><br><span class="line">403</span><br><span class="line">404</span><br><span class="line">405</span><br><span class="line">406</span><br><span class="line">407</span><br><span class="line">408</span><br><span class="line">409</span><br><span class="line">410</span><br><span class="line">411</span><br><span class="line">412</span><br><span class="line">413</span><br><span class="line">414</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// operators/AllOps.java</span></span><br><span class="line"><span class="comment">// 测试所有基本类型的运算符操作</span></span><br><span class="line"><span class="comment">// 看看哪些是能被 Java 编译器接受的</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">AllOps</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 布尔值的接收测试：</span></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">f</span><span class="params">(<span class="keyword">boolean</span> b)</span> </span>&#123;&#125;</span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">boolTest</span><span class="params">(<span class="keyword">boolean</span> x, <span class="keyword">boolean</span> y)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// 算数运算符：</span></span><br><span class="line">        <span class="comment">//- x = x * y;</span></span><br><span class="line">        <span class="comment">//- x = x / y;</span></span><br><span class="line">        <span class="comment">//- x = x % y;</span></span><br><span class="line">        <span class="comment">//- x = x + y;</span></span><br><span class="line">        <span class="comment">//- x = x - y;</span></span><br><span class="line">        <span class="comment">//- x++;</span></span><br><span class="line">        <span class="comment">//- x--;</span></span><br><span class="line">        <span class="comment">//- x = +y;</span></span><br><span class="line">        <span class="comment">//- x = -y;</span></span><br><span class="line">        <span class="comment">// 关系运算符和逻辑运算符：</span></span><br><span class="line">        <span class="comment">//- f(x &gt; y);</span></span><br><span class="line">        <span class="comment">//- f(x &gt;= y);</span></span><br><span class="line">        <span class="comment">//- f(x &lt; y);</span></span><br><span class="line">        <span class="comment">//- f(x &lt;= y);</span></span><br><span class="line">        f(x == y);</span><br><span class="line">        f(x != y);</span><br><span class="line">        f(!y);</span><br><span class="line">        x = x &amp;&amp; y;</span><br><span class="line">        x = x || y;</span><br><span class="line">        <span class="comment">// 按位运算符：</span></span><br><span class="line">        <span class="comment">//- x = ~y;</span></span><br><span class="line">        x = x &amp; y;</span><br><span class="line">        x = x | y;</span><br><span class="line">        x = x ^ y;</span><br><span class="line">        <span class="comment">//- x = x &lt;&lt; 1;</span></span><br><span class="line">        <span class="comment">//- x = x &gt;&gt; 1;</span></span><br><span class="line">        <span class="comment">//- x = x &gt;&gt;&gt; 1;</span></span><br><span class="line">        <span class="comment">// 联合赋值：</span></span><br><span class="line">        <span class="comment">//- x += y;</span></span><br><span class="line">        <span class="comment">//- x -= y;</span></span><br><span class="line">        <span class="comment">//- x *= y;</span></span><br><span class="line">        <span class="comment">//- x /= y;</span></span><br><span class="line">        <span class="comment">//- x %= y;</span></span><br><span class="line">        <span class="comment">//- x &lt;&lt;= 1;</span></span><br><span class="line">        <span class="comment">//- x &gt;&gt;= 1;</span></span><br><span class="line">        <span class="comment">//- x &gt;&gt;&gt;= 1;</span></span><br><span class="line">        x &amp;= y;</span><br><span class="line">        x ^= y;</span><br><span class="line">        x |= y;</span><br><span class="line">        <span class="comment">// 类型转换：</span></span><br><span class="line">        <span class="comment">//- char c = (char)x;</span></span><br><span class="line">        <span class="comment">//- byte b = (byte)x;</span></span><br><span class="line">        <span class="comment">//- short s = (short)x;</span></span><br><span class="line">        <span class="comment">//- int i = (int)x;</span></span><br><span class="line">        <span class="comment">//- long l = (long)x;</span></span><br><span class="line">        <span class="comment">//- float f = (float)x;</span></span><br><span class="line">        <span class="comment">//- double d = (double)x;</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">charTest</span><span class="params">(<span class="keyword">char</span> x, <span class="keyword">char</span> y)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// 算数运算符：</span></span><br><span class="line">        x = (<span class="keyword">char</span>)(x * y);</span><br><span class="line">        x = (<span class="keyword">char</span>)(x / y);</span><br><span class="line">        x = (<span class="keyword">char</span>)(x % y);</span><br><span class="line">        x = (<span class="keyword">char</span>)(x + y);</span><br><span class="line">        x = (<span class="keyword">char</span>)(x - y);</span><br><span class="line">        x++;</span><br><span class="line">        x--;</span><br><span class="line">        x = (<span class="keyword">char</span>) + y;</span><br><span class="line">        x = (<span class="keyword">char</span>) - y;</span><br><span class="line">        <span class="comment">// 关系和逻辑运算符：</span></span><br><span class="line">        f(x &gt; y);</span><br><span class="line">        f(x &gt;= y);</span><br><span class="line">        f(x &lt; y);</span><br><span class="line">        f(x &lt;= y);</span><br><span class="line">        f(x == y);</span><br><span class="line">        f(x != y);</span><br><span class="line">        <span class="comment">//- f(!x);</span></span><br><span class="line">        <span class="comment">//- f(x &amp;&amp; y);</span></span><br><span class="line">        <span class="comment">//- f(x || y);</span></span><br><span class="line">        <span class="comment">// 按位运算符：</span></span><br><span class="line">        x= (<span class="keyword">char</span>)~y;</span><br><span class="line">        x = (<span class="keyword">char</span>)(x &amp; y);</span><br><span class="line">        x = (<span class="keyword">char</span>)(x | y);</span><br><span class="line">        x = (<span class="keyword">char</span>)(x ^ y);</span><br><span class="line">        x = (<span class="keyword">char</span>)(x &lt;&lt; <span class="number">1</span>);</span><br><span class="line">        x = (<span class="keyword">char</span>)(x &gt;&gt; <span class="number">1</span>);</span><br><span class="line">        x = (<span class="keyword">char</span>)(x &gt;&gt;&gt; <span class="number">1</span>);</span><br><span class="line">        <span class="comment">// 联合赋值：</span></span><br><span class="line">        x += y;</span><br><span class="line">        x -= y;</span><br><span class="line">        x *= y;</span><br><span class="line">        x /= y;</span><br><span class="line">        x %= y;</span><br><span class="line">        x &lt;&lt;= <span class="number">1</span>;</span><br><span class="line">        x &gt;&gt;= <span class="number">1</span>;</span><br><span class="line">        x &gt;&gt;&gt;= <span class="number">1</span>;</span><br><span class="line">        x &amp;= y;</span><br><span class="line">        x ^= y;</span><br><span class="line">        x |= y;</span><br><span class="line">        <span class="comment">// 类型转换</span></span><br><span class="line">        <span class="comment">//- boolean bl = (boolean)x;</span></span><br><span class="line">        <span class="keyword">byte</span> b = (<span class="keyword">byte</span>)x;</span><br><span class="line">        <span class="keyword">short</span> s = (<span class="keyword">short</span>)x;</span><br><span class="line">        <span class="keyword">int</span> i = (<span class="keyword">int</span>)x;</span><br><span class="line">        <span class="keyword">long</span> l = (<span class="keyword">long</span>)x;</span><br><span class="line">        <span class="keyword">float</span> f = (<span class="keyword">float</span>)x;</span><br><span class="line">        <span class="keyword">double</span> d = (<span class="keyword">double</span>)x;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">byteTest</span><span class="params">(<span class="keyword">byte</span> x, <span class="keyword">byte</span> y)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// 算数运算符：</span></span><br><span class="line">        x = (<span class="keyword">byte</span>)(x* y);</span><br><span class="line">        x = (<span class="keyword">byte</span>)(x / y);</span><br><span class="line">        x = (<span class="keyword">byte</span>)(x % y);</span><br><span class="line">        x = (<span class="keyword">byte</span>)(x + y);</span><br><span class="line">        x = (<span class="keyword">byte</span>)(x - y);</span><br><span class="line">        x++;</span><br><span class="line">        x--;</span><br><span class="line">        x = (<span class="keyword">byte</span>) + y;</span><br><span class="line">        x = (<span class="keyword">byte</span>) - y;</span><br><span class="line">        <span class="comment">// 关系和逻辑运算符：</span></span><br><span class="line">        f(x &gt; y);</span><br><span class="line">        f(x &gt;= y);</span><br><span class="line">        f(x &lt; y);</span><br><span class="line">        f(x &lt;= y);</span><br><span class="line">        f(x == y);</span><br><span class="line">        f(x != y);</span><br><span class="line">        <span class="comment">//- f(!x);</span></span><br><span class="line">        <span class="comment">//- f(x &amp;&amp; y);</span></span><br><span class="line">        <span class="comment">//- f(x || y);</span></span><br><span class="line">        <span class="comment">//按位运算符：</span></span><br><span class="line">        x = (<span class="keyword">byte</span>)~y;</span><br><span class="line">        x = (<span class="keyword">byte</span>)(x &amp; y);</span><br><span class="line">        x = (<span class="keyword">byte</span>)(x | y);</span><br><span class="line">        x = (<span class="keyword">byte</span>)(x ^ y);</span><br><span class="line">        x = (<span class="keyword">byte</span>)(x &lt;&lt; <span class="number">1</span>);</span><br><span class="line">        x = (<span class="keyword">byte</span>)(x &gt;&gt; <span class="number">1</span>);</span><br><span class="line">        x = (<span class="keyword">byte</span>)(x &gt;&gt;&gt; <span class="number">1</span>);</span><br><span class="line">        <span class="comment">// 联合赋值：</span></span><br><span class="line">        x += y;</span><br><span class="line">        x -= y;</span><br><span class="line">        x *= y;</span><br><span class="line">        x /= y;</span><br><span class="line">        x %= y;</span><br><span class="line">        x &lt;&lt;= <span class="number">1</span>;</span><br><span class="line">        x &gt;&gt;= <span class="number">1</span>;</span><br><span class="line">        x &gt;&gt;&gt;= <span class="number">1</span>;</span><br><span class="line">        x &amp;= y;</span><br><span class="line">        x ^= y;</span><br><span class="line">        x |= y;</span><br><span class="line">        <span class="comment">// 类型转换：</span></span><br><span class="line">        <span class="comment">//- boolean bl = (boolean)x;</span></span><br><span class="line">        <span class="keyword">char</span> c = (<span class="keyword">char</span>)x;</span><br><span class="line">        <span class="keyword">short</span> s = (<span class="keyword">short</span>)x;</span><br><span class="line">        <span class="keyword">int</span> i = (<span class="keyword">int</span>)x;</span><br><span class="line">        <span class="keyword">long</span> l = (<span class="keyword">long</span>)x;</span><br><span class="line">        <span class="keyword">float</span> f = (<span class="keyword">float</span>)x;</span><br><span class="line">        <span class="keyword">double</span> d = (<span class="keyword">double</span>)x;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">shortTest</span><span class="params">(<span class="keyword">short</span> x, <span class="keyword">short</span> y)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// 算术运算符：</span></span><br><span class="line">        x = (<span class="keyword">short</span>)(x * y);</span><br><span class="line">        x = (<span class="keyword">short</span>)(x / y);</span><br><span class="line">        x = (<span class="keyword">short</span>)(x % y);</span><br><span class="line">        x = (<span class="keyword">short</span>)(x + y);</span><br><span class="line">        x = (<span class="keyword">short</span>)(x - y);</span><br><span class="line">        x++;</span><br><span class="line">        x--;</span><br><span class="line">        x = (<span class="keyword">short</span>) + y;</span><br><span class="line">        x = (<span class="keyword">short</span>) - y;</span><br><span class="line">        <span class="comment">// 关系和逻辑运算符：</span></span><br><span class="line">        f(x &gt; y);</span><br><span class="line">        f(x &gt;= y);</span><br><span class="line">        f(x &lt; y);</span><br><span class="line">        f(x &lt;= y);</span><br><span class="line">        f(x == y);</span><br><span class="line">        f(x != y);</span><br><span class="line">        <span class="comment">//- f(!x);</span></span><br><span class="line">        <span class="comment">//- f(x &amp;&amp; y);</span></span><br><span class="line">        <span class="comment">//- f(x || y);</span></span><br><span class="line">        <span class="comment">// 按位运算符：</span></span><br><span class="line">        x = (<span class="keyword">short</span>) ~ y;</span><br><span class="line">        x = (<span class="keyword">short</span>)(x &amp; y);</span><br><span class="line">        x = (<span class="keyword">short</span>)(x | y);</span><br><span class="line">        x = (<span class="keyword">short</span>)(x ^ y);</span><br><span class="line">        x = (<span class="keyword">short</span>)(x &lt;&lt; <span class="number">1</span>);</span><br><span class="line">        x = (<span class="keyword">short</span>)(x &gt;&gt; <span class="number">1</span>);</span><br><span class="line">        x = (<span class="keyword">short</span>)(x &gt;&gt;&gt; <span class="number">1</span>);</span><br><span class="line">        <span class="comment">// Compound assignment:</span></span><br><span class="line">        x += y;</span><br><span class="line">        x -= y;</span><br><span class="line">        x *= y;</span><br><span class="line">        x /= y;</span><br><span class="line">        x %= y;</span><br><span class="line">        x &lt;&lt;= <span class="number">1</span>;</span><br><span class="line">        x &gt;&gt;= <span class="number">1</span>;</span><br><span class="line">        x &gt;&gt;&gt;= <span class="number">1</span>;</span><br><span class="line">        x &amp;= y;</span><br><span class="line">        x ^= y;</span><br><span class="line">        x |= y;</span><br><span class="line">        <span class="comment">// 类型转换：</span></span><br><span class="line">        <span class="comment">//- boolean bl = (boolean)x;</span></span><br><span class="line">        <span class="keyword">char</span> c = (<span class="keyword">char</span>)x;</span><br><span class="line">        <span class="keyword">byte</span> b = (<span class="keyword">byte</span>)x;</span><br><span class="line">        <span class="keyword">int</span> i = (<span class="keyword">int</span>)x;</span><br><span class="line">        <span class="keyword">long</span> l = (<span class="keyword">long</span>)x;</span><br><span class="line">        <span class="keyword">float</span> f = (<span class="keyword">float</span>)x;</span><br><span class="line">        <span class="keyword">double</span> d = (<span class="keyword">double</span>)x;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">intTest</span><span class="params">(<span class="keyword">int</span> x, <span class="keyword">int</span> y)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// 算术运算符：</span></span><br><span class="line">        x = x * y;</span><br><span class="line">        x = x / y;</span><br><span class="line">        x = x % y;</span><br><span class="line">        x = x + y;</span><br><span class="line">        x = x - y;</span><br><span class="line">        x++;</span><br><span class="line">        x--;</span><br><span class="line">        x = +y;</span><br><span class="line">        x = -y;</span><br><span class="line">        <span class="comment">// 关系和逻辑运算符：</span></span><br><span class="line">        f(x &gt; y);</span><br><span class="line">        f(x &gt;= y);</span><br><span class="line">        f(x &lt; y);</span><br><span class="line">        f(x &lt;= y);</span><br><span class="line">        f(x == y);</span><br><span class="line">        f(x != y);</span><br><span class="line">        <span class="comment">//- f(!x);</span></span><br><span class="line">        <span class="comment">//- f(x &amp;&amp; y);</span></span><br><span class="line">        <span class="comment">//- f(x || y);</span></span><br><span class="line">        <span class="comment">// 按位运算符：</span></span><br><span class="line">        x = ~y;</span><br><span class="line">        x = x &amp; y;</span><br><span class="line">        x = x | y;</span><br><span class="line">        x = x ^ y;</span><br><span class="line">        x = x &lt;&lt; <span class="number">1</span>;</span><br><span class="line">        x = x &gt;&gt; <span class="number">1</span>;</span><br><span class="line">        x = x &gt;&gt;&gt; <span class="number">1</span>;</span><br><span class="line">        <span class="comment">// 联合赋值：</span></span><br><span class="line">        x += y;</span><br><span class="line">        x -= y;</span><br><span class="line">        x *= y;</span><br><span class="line">        x /= y;</span><br><span class="line">        x %= y;</span><br><span class="line">        x &lt;&lt;= <span class="number">1</span>;</span><br><span class="line">        x &gt;&gt;= <span class="number">1</span>;</span><br><span class="line">        x &gt;&gt;&gt;= <span class="number">1</span>;</span><br><span class="line">        x &amp;= y;</span><br><span class="line">        x ^= y;</span><br><span class="line">        x |= y;</span><br><span class="line">        <span class="comment">// 类型转换：</span></span><br><span class="line">        <span class="comment">//- boolean bl = (boolean)x;</span></span><br><span class="line">        <span class="keyword">char</span> c = (<span class="keyword">char</span>)x;</span><br><span class="line">        <span class="keyword">byte</span> b = (<span class="keyword">byte</span>)x;</span><br><span class="line">        <span class="keyword">short</span> s = (<span class="keyword">short</span>)x;</span><br><span class="line">        <span class="keyword">long</span> l = (<span class="keyword">long</span>)x;</span><br><span class="line">        <span class="keyword">float</span> f = (<span class="keyword">float</span>)x;</span><br><span class="line">        <span class="keyword">double</span> d = (<span class="keyword">double</span>)x;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">longTest</span><span class="params">(<span class="keyword">long</span> x, <span class="keyword">long</span> y)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// 算数运算符：</span></span><br><span class="line">        x = x * y;</span><br><span class="line">        x = x / y;</span><br><span class="line">        x = x % y;</span><br><span class="line">        x = x + y;</span><br><span class="line">        x = x - y;</span><br><span class="line">        x++;</span><br><span class="line">        x--;</span><br><span class="line">        x = +y;</span><br><span class="line">        x = -y;</span><br><span class="line">        <span class="comment">// 关系和逻辑运算符：</span></span><br><span class="line">        f(x &gt; y);</span><br><span class="line">        f(x &gt;= y);</span><br><span class="line">        f(x &lt; y);</span><br><span class="line">        f(x &lt;= y);</span><br><span class="line">        f(x == y);</span><br><span class="line">        f(x != y);</span><br><span class="line">        <span class="comment">//- f(!x);</span></span><br><span class="line">        <span class="comment">//- f(x &amp;&amp; y);</span></span><br><span class="line">        <span class="comment">//- f(x || y);</span></span><br><span class="line">        <span class="comment">// 按位运算符：</span></span><br><span class="line">        x = ~y;</span><br><span class="line">        x = x &amp; y;</span><br><span class="line">        x = x | y;</span><br><span class="line">        x = x ^ y;</span><br><span class="line">        x = x &lt;&lt; <span class="number">1</span>;</span><br><span class="line">        x = x &gt;&gt; <span class="number">1</span>;</span><br><span class="line">        x = x &gt;&gt;&gt; <span class="number">1</span>;</span><br><span class="line">        <span class="comment">// 联合赋值：</span></span><br><span class="line">        x += y;</span><br><span class="line">        x -= y;</span><br><span class="line">        x *= y;</span><br><span class="line">        x /= y;</span><br><span class="line">        x %= y;</span><br><span class="line">        x &lt;&lt;= <span class="number">1</span>;</span><br><span class="line">        x &gt;&gt;= <span class="number">1</span>;</span><br><span class="line">        x &gt;&gt;&gt;= <span class="number">1</span>;</span><br><span class="line">        x &amp;= y;</span><br><span class="line">        x ^= y;</span><br><span class="line">        x |= y;</span><br><span class="line">        <span class="comment">// 类型转换：</span></span><br><span class="line">        <span class="comment">//- boolean bl = (boolean)x;</span></span><br><span class="line">        <span class="keyword">char</span> c = (<span class="keyword">char</span>)x;</span><br><span class="line">        <span class="keyword">byte</span> b = (<span class="keyword">byte</span>)x;</span><br><span class="line">        <span class="keyword">short</span> s = (<span class="keyword">short</span>)x;</span><br><span class="line">        <span class="keyword">int</span> i = (<span class="keyword">int</span>)x;</span><br><span class="line">        <span class="keyword">float</span> f = (<span class="keyword">float</span>)x;</span><br><span class="line">        <span class="keyword">double</span> d = (<span class="keyword">double</span>)x;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">floatTest</span><span class="params">(<span class="keyword">float</span> x, <span class="keyword">float</span> y)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// 算数运算符：</span></span><br><span class="line">        x = x * y;</span><br><span class="line">        x = x / y;</span><br><span class="line">        x = x % y;</span><br><span class="line">        x = x + y;</span><br><span class="line">        x = x - y;</span><br><span class="line">        x++;</span><br><span class="line">        x--;</span><br><span class="line">        x = +y;</span><br><span class="line">        x = -y;</span><br><span class="line">        <span class="comment">// 关系和逻辑运算符：</span></span><br><span class="line">        f(x &gt; y);</span><br><span class="line">        f(x &gt;= y);</span><br><span class="line">        f(x &lt; y);</span><br><span class="line">        f(x &lt;= y);</span><br><span class="line">        f(x == y);</span><br><span class="line">        f(x != y);</span><br><span class="line">        <span class="comment">//- f(!x);</span></span><br><span class="line">        <span class="comment">//- f(x &amp;&amp; y);</span></span><br><span class="line">        <span class="comment">//- f(x || y);</span></span><br><span class="line">        <span class="comment">// 按位运算符：</span></span><br><span class="line">        <span class="comment">//- x = ~y;</span></span><br><span class="line">        <span class="comment">//- x = x &amp; y;</span></span><br><span class="line">        <span class="comment">//- x = x | y;</span></span><br><span class="line">        <span class="comment">//- x = x ^ y;</span></span><br><span class="line">        <span class="comment">//- x = x &lt;&lt; 1;</span></span><br><span class="line">        <span class="comment">//- x = x &gt;&gt; 1;</span></span><br><span class="line">        <span class="comment">//- x = x &gt;&gt;&gt; 1;</span></span><br><span class="line">        <span class="comment">// 联合赋值：</span></span><br><span class="line">        x += y;</span><br><span class="line">        x -= y;</span><br><span class="line">        x *= y;</span><br><span class="line">        x /= y;</span><br><span class="line">        x %= y;</span><br><span class="line">        <span class="comment">//- x &lt;&lt;= 1;</span></span><br><span class="line">        <span class="comment">//- x &gt;&gt;= 1;</span></span><br><span class="line">        <span class="comment">//- x &gt;&gt;&gt;= 1;</span></span><br><span class="line">        <span class="comment">//- x &amp;= y;</span></span><br><span class="line">        <span class="comment">//- x ^= y;</span></span><br><span class="line">        <span class="comment">//- x |= y;</span></span><br><span class="line">        <span class="comment">// 类型转换：</span></span><br><span class="line">        <span class="comment">//- boolean bl = (boolean)x;</span></span><br><span class="line">        <span class="keyword">char</span> c = (<span class="keyword">char</span>)x;</span><br><span class="line">        <span class="keyword">byte</span> b = (<span class="keyword">byte</span>)x;</span><br><span class="line">        <span class="keyword">short</span> s = (<span class="keyword">short</span>)x;</span><br><span class="line">        <span class="keyword">int</span> i = (<span class="keyword">int</span>)x;</span><br><span class="line">        <span class="keyword">long</span> l = (<span class="keyword">long</span>)x;</span><br><span class="line">        <span class="keyword">double</span> d = (<span class="keyword">double</span>)x;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">doubleTest</span><span class="params">(<span class="keyword">double</span> x, <span class="keyword">double</span> y)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// 算术运算符：</span></span><br><span class="line">        x = x * y;</span><br><span class="line">        x = x / y;</span><br><span class="line">        x = x % y;</span><br><span class="line">        x = x + y;</span><br><span class="line">        x = x - y;</span><br><span class="line">        x++;</span><br><span class="line">        x--;</span><br><span class="line">        x = +y;</span><br><span class="line">        x = -y;</span><br><span class="line">        <span class="comment">// 关系和逻辑运算符：</span></span><br><span class="line">        f(x &gt; y);</span><br><span class="line">        f(x &gt;= y);</span><br><span class="line">        f(x &lt; y);</span><br><span class="line">        f(x &lt;= y);</span><br><span class="line">        f(x == y);</span><br><span class="line">        f(x != y);</span><br><span class="line">        <span class="comment">//- f(!x);</span></span><br><span class="line">        <span class="comment">//- f(x &amp;&amp; y);</span></span><br><span class="line">        <span class="comment">//- f(x || y);</span></span><br><span class="line">        <span class="comment">// 按位运算符：</span></span><br><span class="line">        <span class="comment">//- x = ~y;</span></span><br><span class="line">        <span class="comment">//- x = x &amp; y;</span></span><br><span class="line">        <span class="comment">//- x = x | y;</span></span><br><span class="line">        <span class="comment">//- x = x ^ y;</span></span><br><span class="line">        <span class="comment">//- x = x &lt;&lt; 1;</span></span><br><span class="line">        <span class="comment">//- x = x &gt;&gt; 1;</span></span><br><span class="line">        <span class="comment">//- x = x &gt;&gt;&gt; 1;</span></span><br><span class="line">        <span class="comment">// 联合赋值：</span></span><br><span class="line">        x += y;</span><br><span class="line">        x -= y;</span><br><span class="line">        x *= y;</span><br><span class="line">        x /= y;</span><br><span class="line">        x %= y;</span><br><span class="line">        <span class="comment">//- x &lt;&lt;= 1;</span></span><br><span class="line">        <span class="comment">//- x &gt;&gt;= 1;</span></span><br><span class="line">        <span class="comment">//- x &gt;&gt;&gt;= 1;</span></span><br><span class="line">        <span class="comment">//- x &amp;= y;</span></span><br><span class="line">        <span class="comment">//- x ^= y;</span></span><br><span class="line">        <span class="comment">//- x |= y;</span></span><br><span class="line">        <span class="comment">// 类型转换：</span></span><br><span class="line">        <span class="comment">//- boolean bl = (boolean)x;</span></span><br><span class="line">        <span class="keyword">char</span> c = (<span class="keyword">char</span>)x;</span><br><span class="line">        <span class="keyword">byte</span> b = (<span class="keyword">byte</span>)x;</span><br><span class="line">        <span class="keyword">short</span> s = (<span class="keyword">short</span>)x;</span><br><span class="line">        <span class="keyword">int</span> i = (<span class="keyword">int</span>)x;</span><br><span class="line">        <span class="keyword">long</span> l = (<span class="keyword">long</span>)x;</span><br><span class="line">        <span class="keyword">float</span> f = (<span class="keyword">float</span>)x;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>注意</strong> ：<strong>boolean</strong> 类型的运算是受限的。你能为其赋值 <code>true</code> 或 <code>false</code>，也可测试它的值是否是 <code>true</code> 或 <code>false</code>。但你不能对其作加减等其他运算。</p>
<p>在 <strong>char</strong>，<strong>byte</strong> 和 <strong>short</strong> 类型中，我们可以看到算术运算符的“类型转换”效果。我们必须要显式强制类型转换才能将结果重新赋值为原始类型。对于 <strong>int</strong> 类型的运算则不用转换，因为默认就是 <strong>int</strong> 型。虽然我们不用再停下来思考这一切是否安全，但是两个大的 int 型整数相乘时，结果有可能超出 <strong>int</strong> 型的范围，这种情况下结果会发生溢出。下面的代码示例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// operators/Overflow.java</span></span><br><span class="line"><span class="comment">// 厉害了！内存溢出</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Overflow</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> big = Integer.MAX_VALUE;</span><br><span class="line">        System.out.println(<span class="string">"big = "</span> + big);</span><br><span class="line">        <span class="keyword">int</span> bigger = big * <span class="number">4</span>;</span><br><span class="line">        System.out.println(<span class="string">"bigger = "</span> + bigger);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>输出结果：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">big &#x3D; 2147483647</span><br><span class="line">bigger &#x3D; -4</span><br></pre></td></tr></table></figure>

<p>编译器没有报错或警告，运行时一切看起来都无异常。诚然，Java 是优秀的，但是还不足够优秀。</p>
<p>对于 <strong>char</strong>，<strong>byte</strong> 或者 <strong>short</strong>，混合赋值并不需要类型转换。即使为它们执行转型操作，也会获得与直接算术运算相同的结果。另外，省略类型转换可以使代码显得更加简练。总之，除 <strong>boolean</strong> 以外，其他任何两种基本类型间都可进行类型转换。当我们进行向下转换类型时，需要注意结果的范围是否溢出，否则我们就很可能在不知不觉中丢失精度。</p>
<!-- Summary -->
<h2 id="本章小结"><a href="#本章小结" class="headerlink" title="本章小结"></a>本章小结</h2><p>如果你已接触过一门 C 语法风格编程语言，那么你在学习 Java 的运算符时实际上没有任何曲线。如果你觉得有难度，那么我推荐你要先去 <a href="http://www.OnJava8.com" target="_blank" rel="noopener">www.OnJava8.com</a> 观看 《Thinking in C》 的视频教程来补充一些前置知识储备。</p>
<p>[^1]: 我在 <em>Pomona College</em> 大学读过两年本科，在那里 47 被称之为“魔法数字”（<em>magic number</em>），详见 <a href="https://en.wikipedia.org/wiki/47_(number)" target="_blank" rel="noopener">维基百科</a> 。</p>
<p>[^2]: <em>John Kirkham</em> 说过：“自 1960 年我开始在 IBM 1620 上开始编程起，至 1970 年之间，FORTRAN 一直都是一种全大写的编程语言。这可能是因为许多早期的输入设备都是旧的电传打字机，使用了 5 位波特码，没有小写字母的功能。指数符号中的 e 也总是大写的，并且从未与自然对数底数 e 混淆，自然对数底数 e 总是小写的。 e 简单地代表指数，通常 10 是基数。那时，八进制也被程序员广泛使用。虽然我从未见过它的用法，但如果我看到一个指数符号的八进制数，我会认为它是以 8 为基数的。我记得第一次看到指数使用小写字母 e 是在 20 世纪 70 年代末，我也发现它令人困惑。这个问题出现的时候，小写字母悄悄进入了 Fortran。如果你真的想使用自然对数底，我们实际上有一些函数要使用，但是它们都是大写的。”</p>
<!-- 分页 -->
<div style="page-break-after: always;"></div>
 
      <!-- reward -->
      
    </div>
    

    <!-- copyright -->
    
    <footer class="article-footer">
       
<div class="share-btn">
      <span class="share-sns share-outer">
        <i class="ri-share-forward-line"></i>
        分享
      </span>
      <div class="share-wrap">
        <i class="arrow"></i>
        <div class="share-icons">
          
          <a class="weibo share-sns" href="javascript:;" data-type="weibo">
            <i class="ri-weibo-fill"></i>
          </a>
          <a class="weixin share-sns wxFab" href="javascript:;" data-type="weixin">
            <i class="ri-wechat-fill"></i>
          </a>
          <a class="qq share-sns" href="javascript:;" data-type="qq">
            <i class="ri-qq-fill"></i>
          </a>
          <a class="douban share-sns" href="javascript:;" data-type="douban">
            <i class="ri-douban-line"></i>
          </a>
          <!-- <a class="qzone share-sns" href="javascript:;" data-type="qzone">
            <i class="icon icon-qzone"></i>
          </a> -->
          
          <a class="facebook share-sns" href="javascript:;" data-type="facebook">
            <i class="ri-facebook-circle-fill"></i>
          </a>
          <a class="twitter share-sns" href="javascript:;" data-type="twitter">
            <i class="ri-twitter-fill"></i>
          </a>
          <a class="google share-sns" href="javascript:;" data-type="google">
            <i class="ri-google-fill"></i>
          </a>
        </div>
      </div>
</div>

<div class="wx-share-modal">
    <a class="modal-close" href="javascript:;"><i class="ri-close-circle-line"></i></a>
    <p>扫一扫，分享到微信</p>
    <div class="wx-qrcode">
      <img src="//api.qrserver.com/v1/create-qr-code/?size=150x150&data=http://yoursite.com/2020/07/25/%E7%AC%AC%E5%9B%9B%E7%AB%A0%20%E8%BF%90%E7%AE%97%E7%AC%A6/" alt="微信分享二维码">
    </div>
</div>

<div id="share-mask"></div>  
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Java%E7%BC%96%E7%A8%8B%E6%80%9D%E6%83%B3/" rel="tag">Java编程思想</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/OnJava8/" rel="tag">OnJava8</a></li></ul>

    </footer>
  </div>

   
  <nav class="article-nav">
    
      <a href="/2020/07/26/%E7%AC%AC%E4%BA%94%E7%AB%A0%20%E6%8E%A7%E5%88%B6%E6%B5%81/" class="article-nav-link">
        <strong class="article-nav-caption">上一篇</strong>
        <div class="article-nav-title">
          
            第五章 控制流
          
        </div>
      </a>
    
    
      <a href="/2020/07/24/%E7%AC%AC%E4%B8%89%E7%AB%A0%20%E4%B8%87%E7%89%A9%E7%9A%86%E5%AF%B9%E8%B1%A1/" class="article-nav-link">
        <strong class="article-nav-caption">下一篇</strong>
        <div class="article-nav-title">第三章 万物皆对象</div>
      </a>
    
  </nav>

   
<!-- valine评论 -->
<div id="vcomments-box">
  <div id="vcomments"></div>
</div>
<script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/valine@1.4.14/dist/Valine.min.js"></script>
<script>
  new Valine({
    el: "#vcomments",
    app_id: "",
    app_key: "",
    path: window.location.pathname,
    avatar: "monsterid",
    placeholder: "给我的文章加点评论吧~",
    recordIP: true,
  });
  const infoEle = document.querySelector("#vcomments .info");
  if (infoEle && infoEle.childNodes && infoEle.childNodes.length > 0) {
    infoEle.childNodes.forEach(function (item) {
      item.parentNode.removeChild(item);
    });
  }
</script>
<style>
  #vcomments-box {
    padding: 5px 30px;
  }

  @media screen and (max-width: 800px) {
    #vcomments-box {
      padding: 5px 0px;
    }
  }

  #vcomments-box #vcomments {
    background-color: #fff;
  }

  .v .vlist .vcard .vh {
    padding-right: 20px;
  }

  .v .vlist .vcard {
    padding-left: 10px;
  }
</style>

 
     
</article>

</section>
      <footer class="footer">
  <div class="outer">
    <ul>
      <li>
        Copyrights &copy;
        2015-2020
        <i class="ri-heart-fill heart_icon"></i> Gghui
      </li>
    </ul>
  </div>
</footer>
      <div class="float_btns">
        <div class="totop" id="totop">
  <i class="ri-arrow-up-line"></i>
</div>

<div class="todark" id="todark">
  <i class="ri-moon-line"></i>
</div>

      </div>
    </main>
    <aside class="sidebar on">
      <button class="navbar-toggle"></button>
<nav class="navbar">
  
  <div class="logo">
    <a href="/"><img src="/images/ayer-side.svg" alt="歆雨小屋"></a>
  </div>
  
  <ul class="nav nav-main">
    
    <li class="nav-item">
      <a class="nav-item-link" href="/">主页</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/archives">归档</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/categories">分类</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags">标签</a>
    </li>
    
  </ul>
</nav>
<nav class="navbar navbar-bottom">
  <ul class="nav">
    <li class="nav-item">
      
      <a class="nav-item-link nav-item-search"  title="Search">
        <i class="ri-search-line"></i>
      </a>
      
      
      <a class="nav-item-link" target="_blank" href="/atom.xml" title="RSS Feed">
        <i class="ri-rss-line"></i>
      </a>
      
    </li>
  </ul>
</nav>
<div class="search-form-wrap">
  <div class="local-search local-search-plugin">
  <input type="search" id="local-search-input" class="local-search-input" placeholder="Search...">
  <div id="local-search-result" class="local-search-result"></div>
</div>
</div>
    </aside>
    <script>
      if (window.matchMedia("(max-width: 768px)").matches) {
        document.querySelector('.content').classList.remove('on');
        document.querySelector('.sidebar').classList.remove('on');
      }
    </script>
    <div id="mask"></div>

<!-- #reward -->
<div id="reward">
  <span class="close"><i class="ri-close-line"></i></span>
  <p class="reward-p"><i class="ri-cup-line"></i>请我喝杯咖啡吧~</p>
  <div class="reward-box">
    
    <div class="reward-item">
      <img class="reward-img" src="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/img/alipay.jpg">
      <span class="reward-type">支付宝</span>
    </div>
    
    
    <div class="reward-item">
      <img class="reward-img" src="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/img/wechat.jpg">
      <span class="reward-type">微信</span>
    </div>
    
  </div>
</div>
    
<script src="/js/jquery-2.0.3.min.js"></script>


<script src="/js/lazyload.min.js"></script>

<!-- Tocbot -->


<script src="/js/tocbot.min.js"></script>

<script>
  tocbot.init({
    tocSelector: '.tocbot',
    contentSelector: '.article-entry',
    headingSelector: 'h1, h2, h3, h4, h5, h6',
    hasInnerContainers: true,
    scrollSmooth: true,
    scrollContainer: 'main',
    positionFixedSelector: '.tocbot',
    positionFixedClass: 'is-position-fixed',
    fixedSidebarOffset: 'auto'
  });
</script>

<script src="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.css">
<script src="https://cdn.jsdelivr.net/npm/justifiedGallery@3.7.0/dist/js/jquery.justifiedGallery.min.js"></script>

<script src="/dist/main.js"></script>

<!-- ImageViewer -->

<!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>

    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">

        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>

        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">

            <div class="pswp__top-bar">

                <!--  Controls are self-explanatory. Order can be changed. -->

                <div class="pswp__counter"></div>

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

                <button class="pswp__button pswp__button--share" style="display:none" title="Share"></button>

                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                        <div class="pswp__preloader__cut">
                            <div class="pswp__preloader__donut"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div>
            </div>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>

            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>

            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>

        </div>

    </div>

</div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/default-skin/default-skin.min.css">
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe-ui-default.min.js"></script>

<script>
    function viewer_init() {
        let pswpElement = document.querySelectorAll('.pswp')[0];
        let $imgArr = document.querySelectorAll(('.article-entry img:not(.reward-img)'))

        $imgArr.forEach(($em, i) => {
            $em.onclick = () => {
                // slider展开状态
                // todo: 这样不好，后面改成状态
                if (document.querySelector('.left-col.show')) return
                let items = []
                $imgArr.forEach(($em2, i2) => {
                    let img = $em2.getAttribute('data-idx', i2)
                    let src = $em2.getAttribute('data-target') || $em2.getAttribute('src')
                    let title = $em2.getAttribute('alt')
                    // 获得原图尺寸
                    const image = new Image()
                    image.src = src
                    items.push({
                        src: src,
                        w: image.width || $em2.width,
                        h: image.height || $em2.height,
                        title: title
                    })
                })
                var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, {
                    index: parseInt(i)
                });
                gallery.init()
            }
        })
    }
    viewer_init()
</script>

<!-- MathJax -->

<!-- Katex -->

<!-- busuanzi  -->


<script src="/js/busuanzi-2.3.pure.min.js"></script>


<!-- ClickLove -->

<!-- ClickBoom1 -->

<!-- ClickBoom2 -->

<!-- CodeCopy -->


<link rel="stylesheet" href="/css/clipboard.css">

<script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>
<script>
  function wait(callback, seconds) {
    var timelag = null;
    timelag = window.setTimeout(callback, seconds);
  }
  !function (e, t, a) {
    var initCopyCode = function(){
      var copyHtml = '';
      copyHtml += '<button class="btn-copy" data-clipboard-snippet="">';
      copyHtml += '<i class="ri-file-copy-2-line"></i><span>COPY</span>';
      copyHtml += '</button>';
      $(".highlight .code pre").before(copyHtml);
      $(".article pre code").before(copyHtml);
      var clipboard = new ClipboardJS('.btn-copy', {
        target: function(trigger) {
          return trigger.nextElementSibling;
        }
      });
      clipboard.on('success', function(e) {
        let $btn = $(e.trigger);
        $btn.addClass('copied');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-checkbox-circle-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPIED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-checkbox-circle-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
      clipboard.on('error', function(e) {
        e.clearSelection();
        let $btn = $(e.trigger);
        $btn.addClass('copy-failed');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-time-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPY FAILED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-time-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
    }
    initCopyCode();
  }(window, document);
</script>


<!-- CanvasBackground -->


    
    <div id="music">
    
    
    
    <iframe frameborder="no" border="1" marginwidth="0" marginheight="0" width="200" height="52"
        src="//music.163.com/outchain/player?type=2&id=371362&auto=1&height=32"></iframe>
</div>

<style>
    #music {
        position: fixed;
        right: 15px;
        bottom: 0;
        z-index: 998;
    }
</style>
    
  </div>
</body>

</html>